之前学习的几个排序又忘记了,今天回顾《数据结构与算法(java描述)》这本书的时候才又不得不花时间来搞懂,其中比较难理解和难实现的就是堆排序和快速排序了吧。
快速排序的算法:
实现代码:
private static final int CUTOFF = 3;
public static <AnyType extends Comparable<? super AnyType>>
void quickSort(AnyType[] arr) {
quickSort(arr, 0, arr.length - 1);
}
private static <AnyType extends Comparable<? super AnyType>>
void quickSort(AnyType[] a, int left, int right) {
if (left == right) {
return;
}
if (left + CUTOFF <= right) {
AnyType pivot = median3(a, left, right);
// Begin partitioning
int i = left, j = right - 1;
for (; ; ) {
while (a[++i].compareTo(pivot) < 0) {
}
while (a[--j].compareTo(pivot) > 0) {
}
if (i < j)
swapReferences(a, i, j);
else
break;
}
swapReferences(a, i, right - 1); // Restore pivot
quickSort(a, left, i - 1); // Sort small elements
quickSort(a, i + 1, right);
} else {
insertionSort(a);
}
}
private static <AnyType extends Comparable<? super AnyType>>
void insertionSort(AnyType[] a, int left, int right) {
for (int p = left + 1; p <= right; p++) {
AnyType tmp = a[p];
int j;
for (j = p; j > left && tmp.compareTo(a[j - 1]) < 0; j--)
a[j] = a[j - 1];
a[j] = tmp;
}
}
private static <AnyType extends Comparable<? super AnyType>>
AnyType median3(AnyType[] a, int left, int right) {
int center = (left + right) / 2;
if (a[center].compareTo(a[left]) < 0)
swapReferences(a, left, center);
if (a[right].compareTo(a[left]) < 0)
swapReferences(a, left, right);
if (a[right].compareTo(a[center]) < 0)
swapReferences(a, center, right);
// Place pivot at position right - 1
swapReferences(a, center, right - 1);
return a[right - 1];
}
public static <AnyType> void swapReferences(AnyType[] a, int index1, int index2) {
AnyType tmp = a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}