指令是编辑一个快速排序程序,以选择三个中位数作为枢轴,而不是数组的第一个值。
为此,我对代码进行了如下编辑:
public class medianOf3 {
//Main method and test array
public static void main(String[] args) {
int[] list = {2,3,2,5,6,1,-2,14,12};
quickSort(list);
for (int i = 0; i < list.length; i++)
System.out.print(list[i] + " ");
System.out.println();
}
public static void quickSort(int[] list) {
quickSort(list,list.length - 1);
}
//The quicksort method
public static void quickSort(int[] list,int first,int last) {
if (last > first) {
int pivotIndex = partition(list,first,last);
quickSort(list,pivotIndex - 1);
quickSort(list,pivotIndex + 1,last);
}
}
// Returns the median of three integers
public static int median(int first,int middle,int last) {
return Math.max(Math.min(first,middle),Math.min(Math.max(first,last));
}
//returns the index of a value
public static int findIndex (int[] list,int t) {
if (list == null) return -1;
int len = list.length;
int i = 0;
while (i < len) {
if (list[i] == t) return i;
else i=i+1;
}
return -1;
}
public static int partition(int[] list,int last) {
int middle = ((last-first) / 2)+first;
int pivot = median(list[first],list[middle],list[last]); // selecting the median of three (of the first,middle and last value) as the pivot
int low = first +1; // Index for forward search
int high = last; // Index for backward search
int index = findIndex(list,pivot );
int swap = list[index];
list[index] = list[0];
list[0] = swap;
while (high > low) {
// Search forward from left
while (low <= high && list[low] <= pivot)
low++;
// Search backward from right
while (low <= high && list[high] > pivot)
high--;
// Swap two elements in the list
if (high > low) {
int temp = list[high];
list[high] = list[low];
list[low] = temp;
}
}
while (high > first && list[high] >= pivot)
high--;
// Swap pivot with list[high]
if (pivot > list[high]) {
list[first] = list[high];
list[high] = pivot;
return high;
} else { return first;}
}
}
上面的代码返回以下输出:
14 1 2 2 3 3 5 6 12 14
所需的输出是这样:
-2 1 2 2 3 3 5 6 12 14
使用调试器,我可以对要正确排序的数组进行一次计算, 只需交换最后两个值:
-2 1 2 2 3 3 5 6 14 12
在
的最终发行内list[index] = list[0];
使用调试器,分区方法的行是发生错误的地方。我觉得这很可能是一个逻辑错误,但我不确定当时到底出了什么问题。
感谢所有反馈。