因此,显然在某些情况下,我的算法需要较少的透视更改来完成列表的排序。实际上,我的算法确实对列表进行了正确的排序,但数据透视表的数量小于或等于我所给出的示例。我的赋值中给出的一个例子是这个数组:
3 45 12 -3 4 -3 21 0 6 20
输出应该是这样的:
枢轴数: 7
第一个元素: -3
最后一个元素: 45
这是我得到的:
枢轴数: 5
第一个元素: -3
最后一个元素: 45
在另一个例子中,它适用于正确数量的枢轴:
9 2 4 7 3 7 10 11 12 13 13 10 13 13
我应该得到什么,也得到什么:
枢轴数量: 10
第一个元素: 2
最后一个元素: 13
我特别困惑的是,它在某些情况下有效,而在其他情况下则不起作用。
代码如下:
public static void quickSort(int[] arr, int start, int end, CountObject count){
int partition = partition(arr, start, end, count);
//partition will return the position the pivot. The pivot will be at the right place, hence if either side
//of the pivot consists of only one element, it should not be sorted
//check whether the part left from the pivot should still be sorted
if(partition-1>start) {
quickSort(arr, start, partition - 1, count);
}
//check whether the part right from the pivot should still be sorted
if(partition+1<end) {
quickSort(arr, partition + 1, end, count);
}
}
public static int partition(int[] arr, int start, int end, CountObject count){
int pivot = arr[start];
count.increaseCount();
//checks if left pointer < pivot
for(int i=end; i>start; i--){
if(arr[i]>pivot){
int temp= arr[end];
arr[end]=arr[i];
arr[i]=temp;
end--;
}
}
int temp = arr[start];//=pivot
arr[start] = arr[end];
arr[end] = temp;
return end;
}
}
我正在使用 CountObject 类进行计数。它包含一个方法增加计数和一个实例变量计数。
白衣非少年
相关分类