关于快速排序算法的问题
public class QuickSort {
public int[] quickSort(int[] A, int n) {
quickSort(A,0,n-1);
return A;
}
private void quickSort(int[] a, int leftPos, int rightPos) {
if(1<rightPos-leftPos){
int pivot = median3(a, leftPos, rightPos);
int i = leftPos, j = rightPos - 1;
for (;;) {
while (a[++i] < pivot) {
}
while (a[--j] > pivot) {
}
if (i < j) {// 当i还没有超过j的时候
exchangeElements(a, i, j);
} else {
break;
}
}
// 将pivot与i指向的元素交换
exchangeElements(a, i, rightPos - 1);
quickSort(a, leftPos, i - 1);// 递归快速排序左侧序列
quickSort(a, i + 1, rightPos);// 递归快速排序右侧序列
}else{
return;
}
}
private int median3(int[] a, int leftPos, int rightPos) {
int center = (leftPos + rightPos) / 2;
if (a[center] < a[leftPos]) {
exchangeElements(a, center, leftPos);
}
if (a[rightPos] < a[leftPos]) {
exchangeElements(a, rightPos, leftPos);
}// 此时,最小值位于a[leftPos]
if (a[rightPos] < a[center]) {
exchangeElements(a, rightPos, center);
}// 此时,最大值位于a[rightPos],中位数pivot位于a[center]
// 将pivot放置于rightPos-1的位置.
// ∵a[leftPos]一定小于pivot,a[rightPos]一定大于pivot
exchangeElements(a, center, rightPos - 1);
return a[rightPos - 1];
}
//位置互换
private void exchangeElements(int[] array, int index1, int index2) {
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
}
//上面是<<数据结构与算法 --Java语言描述>>中的快速排序算法,为什么我用上述算法在排序时,测试通过率为3.33%,百思不得其解,求各路大神解答
//在此,万分感谢!!!!!!!!!!
#Java工程师##算法工程师#
查看14道真题和解析