我在这里有我的快速排序课程
package week4;
class QuickSort<T extends Comparable<? super T>> {
public void display(T[] array) {
int index;
for (index = 0; index < array.length - 1; index++)
System.out.print(array[index] + ", ");
System.out.println(array[index]);
}
private void swap(T[] a, int i, int j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
display(a);
}
public void order(T[] a, int i, int j) {
if (a[i].compareTo(a[j]) > 0)
swap(a, i, j);
}
public void sortFirstMiddleLast(T[] a, int first, int mid, int last) {
order(a, first, mid); // make a[first] <= a[mid]
order(a, mid, last); // make a[mid] <= a[last]
order(a, first, mid); // make a[first] <= a[mid]
}
public int partition(T[] arr, int first, int last) {
int mid = (first + last) / 2;
sortFirstMiddleLast(arr, first, mid, last);
swap(arr, mid, last - 1);
int pivotIndex = last - 1;
T pivot = arr[pivotIndex];
int indexFromLeft = first + 1;
int indexFromRight = last - 2;
boolean done = false;
while (!done) {
while (arr[indexFromLeft].compareTo(pivot) < 0)
indexFromLeft++;
while (arr[indexFromRight].compareTo(pivot) > 0)
indexFromRight--;
if (indexFromLeft < indexFromRight) {
swap(arr, indexFromLeft, indexFromRight);
indexFromLeft++;
indexFromRight--;
} else
done = true;
}
// place pivot between Smaller and Larger subarrays
swap(arr, pivotIndex, indexFromLeft);
pivotIndex = indexFromLeft;
// Smaller = a[first pivotIndex-1]
// Pivot = a[pivotIndex]
// Larger = a[pivotIndex + 1..the last]
return pivotIndex;
}
}
我的问题是枢轴由于某种原因没有得到排序,我不知道为什么......我试图调试并尝试谷歌,但我无法弄清楚......
阿晨1998
阿波罗的战车
相关分类