我正在尝试选择中位数作为此应用程序中的支点,但似乎我做错了什么。任何帮助将不胜感激。
我按顺序得到前几个数字,然后到最后。
public class QuickSort {
public static void main(String[] args) {
int [] list = {1,3,2,4,6,5,8,7,9,0};
quickSort (list);
for (int i=0; i < list.length; i++)
System.out.print(list[i] + " ");
}
public static void quickSort(int [] list)
{
quickSort(list, 0, list.length - 1);
}
public static void quickSort (int[] list, int first, int last)
{
int size = last - first + 1;
if (size > 3){
int median1 = median(list, first, last);
int partition1 = partition(list, first, last, median1);
quickSort(list, first, partition1 - 1);
quickSort(list, partition1 + 1, last);
}
}
public static int median(int [] list, int first1, int last1){
int middle = (first1 + last1)/2;
if (list[first1] > list[middle])
swap(list, first1, middle);
if (list[first1] > list[last1])
swap(list, first1, last1);
if (list[middle] > list[last1])
swap(list, middle, last1);
swap(list, middle, last1 - 1);
return list[last1 - 1 ];
}
public static int partition(int [] list, int left, int right, long pivot) {
int leftPtr = left;
int rightPtr = right - 1;
while (true) {
while (list[++leftPtr] < pivot);
while (list[--rightPtr] > pivot);
if (leftPtr >= rightPtr)
break;
else
swap(list, leftPtr, rightPtr);
}
swap(list, leftPtr, right - 1);
return leftPtr;
}
public static void swap(int []list, int dex1, int dex2) {
int temp = list[dex1];
list[dex1] = list[dex2];
list[dex2] = temp;
}
我按顺序得到了一些数字,但不是全部。