[英]QuickSort Java code giving error Time Limit Exceeded
I am using the below code to sort out a given array using Quick Sort Algo.我正在使用以下代码使用快速排序算法对给定数组进行排序。 I am a beginner and am struggling to understand why my code runs fine on few test cases but fails on few.
我是一个初学者,正在努力理解为什么我的代码在少数测试用例上运行良好,但在少数情况下失败。 I am receiving error Time Limit Exceeded.
我收到错误 Time Limit Exceeded。 The code is constantly failing the test case :-
array{5,5,6,8,4,5,6}
.代码不断地使测试用例失败:-
array{5,5,6,8,4,5,6}
。 Feel free to give tips on how to code better.随意提供有关如何更好地编码的提示。
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;
}
}
At a glance it seems you're using the indexes as a way to indicate subarray limits乍一看,您似乎正在使用索引作为指示子数组限制的一种方式
public static int partition(int input[] ,int startIndex , int endIndex)
But then you iterate the whole array always ( the condition is i < input.length
) on:但是你总是迭代整个数组(条件是
i < input.length
):
for(int i = 1+startIndex ; i < input.length ; i++){
if(input[i] < pivot){
count++;
}
...
So in your subsequent iterations you're still going through the whole array:因此,在您随后的迭代中,您仍在遍历整个数组:
So in this call:所以在这个电话中:
quickSort(input,startIndex , pivot-1);
pivot -1
is ignored as you go through input.length
anyway causing the guard condition:无论如何,当您通过
input.length
会忽略pivot -1
导致保护条件:
if (startIndex >= endIndex )
to never evaluate to true hence running forever.永远不会评估为真,因此永远运行。
Try changing your for loop to (didn't try this myself, just by looking at the code):尝试将您的 for 循环更改为(我自己没有尝试过,只是通过查看代码):
for(int i = 1+startIndex ; i < endIndex ; i++){
And see if that works.看看这是否有效。
I hope this helps.我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.