我没有从任何地方看到这个算法,我自己做的,只是看看快速排序是如何工作的,这是在Java中,问题是,它可以很好地排序,并且对6个以上的值很好,它挂起的值超过6。或者可能有一些其他的问题,我不知道。这是代码-
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.print("Enter number of elements= ");
int x, a[];
Scanner z = new Scanner(System.in);
x = Integer.parseInt(z.next());
a = new int[x];
for(int i = 0; i < x; i++){
System.out.print("Enter element #"+(i+1)+"= ");
a[i] = Integer.parseInt(z.next());
}
QuickSort(a, 0, x-1);
System.out.print("A= ");
for(int i = 0; i < x; i++){
System.out.print(a[i]+" ");
}
}
public static void QuickSort(int a[], int low, int high){
if(low >= high)
return;
int l = low + 1, h = high, flag = 0, temp;
while(l <= h){
if(a[low] >= a[l]){
++l;
++flag;
}
if(a[low] <a [h]){
--h;
++flag;
} else if(flag == 0){
temp = a[l];
a[l] = a[h];
a[h] = temp;
++l;
--h;
}
}
temp = a[low];
a[low] = a[h];
a[h] = temp;
QuickSort(a, low, h-1);
QuickSort(a, h+1, high);
}
}谢谢你的帮助。
发布于 2013-03-11 22:57:00
问题是您忘记在内部循环中将flag设置回0,从而导致它进入无限循环。
在while(l<=h){之后添加flag=0;行可以使其正常工作。尽管你真的应该学会写代码,但它不是一团乱七八糟的。这不仅会让人们更容易地帮助你,甚至还会让你更容易发现这样的bug。
此外,在寻求帮助之前,您应该真正学习基本的故障排除技能。我甚至不需要使用调试器,我只需要添加几个print语句来查看它在哪里卡住了。
https://stackoverflow.com/questions/15341252
复制相似问题