【发布时间】:2020-05-21 12:17:48
【问题描述】:
我正在使用下面的代码使用快速排序算法对给定的数组进行排序。我是一个初学者,正在努力理解为什么我的代码在少数测试用例上运行良好,但在少数测试用例上却失败了。我收到错误超过时间限制。该代码不断未能通过测试用例:- array{5,5,6,8,4,5,6} 。随时提供有关如何更好地编码的提示。
public static void quickSort(int[] input) {
quickSort(input, 0 , input.length-1) ;
}
public static void quickSort(int input[] , int startIndex , int endIndex) {
if(startIndex >= endIndex){
return;
} else{
int pivot = partition(input, startIndex , endIndex);
quickSort(input,startIndex , pivot-1) ;
quickSort(input , pivot+1 , endIndex) ;
}
}
public static int partition(int input[] ,int startIndex , int endIndex) {
int pivot = input[startIndex] ;
int count = 0;
for(int i = 1+startIndex ; i < input.length ; i++){
if(input[i] < pivot){
count++;
}
}
input[startIndex] = input[startIndex+count];
input[startIndex+count] = pivot ;
int s = startIndex ;
int e = endIndex ;
int sc = startIndex+count;
while(s < sc && sc < e){
if(input[s] < pivot) {
s++;
} else if(input[e] >= pivot){
e--;
}else if(input[s] > pivot && input[e] < pivot){
int temp = input[e];
input[e] = input[s] ;
input[s] = temp;
e--;
s++;
}
}
return sc;
}
}
【问题讨论】:
-
代码修改了 Hoare 分区方案,以便将枢轴放置在适当的位置。这不是必需的。相反,不要从使用 quickSort(... pivot) 和 quicksort(... pivot+1 ...) 的 2 个递归调用中排除枢轴。看看wiki example,它将条件(if 语句)的数量减少到每个内部循环只有 1 个。
标签: java algorithm sorting data-structures quicksort