快速排序Java
您好,我目前正在努力让我的快速排序程序工作,但无法找出哪里出了问题,我花了几个小时试图找出为什么它不工作,但没有运气,当我运行我的代码时,什么都没有发生。我还有其他四种排序算法以类似的方式工作,这是最让我困惑的。 下面是我的快速排序程序代码快速排序Java,java,sorting,quicksort,Java,Sorting,Quicksort,您好,我目前正在努力让我的快速排序程序工作,但无法找出哪里出了问题,我花了几个小时试图找出为什么它不工作,但没有运气,当我运行我的代码时,什么都没有发生。我还有其他四种排序算法以类似的方式工作,这是最让我困惑的。 下面是我的快速排序程序代码 import java.io.IOException; public class QuickSort { public static int[] compute(int[] array, int lower, int higher )throws
import java.io.IOException;
public class QuickSort {
public static int[] compute(int[] array, int lower, int higher )throws IOException{
if(lower<higher){
int pivot=split(array,lower,higher);
if(pivot>1)
compute(array, lower, pivot-1);
if(pivot+1<higher)
compute(array, pivot+1, higher);
}
return array;
}
public static int split(int[] array, int lower, int higher){
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
}
else{
return higher;
}
}
}
import java.io.IOException;
公共类快速排序{
公共静态int[]计算(int[]数组,int更低,int更高)引发IOException{
如果(低1)
计算(数组,更低,pivot-1);
如果(pivot+1看起来你的程序什么都没做,它可能只是在这个循环中无限循环:
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
// I recommend adding this line for you to see what's going on
System.out.println("lower="+lower+", higher="+higher+", pivot="+pivot);
}
else{
return higher;
}
}
此外,在上面的循环中,我添加了更高、更低和轴心值的额外打印输出,这将帮助您看到在这个迂回的循环中发生了什么
一般来说,写一段时间(对)循环不是一种好的做法,因为它很容易将系统挂起。如果输入中有重复的数字,则快速排序代码将永远循环,因为这些数字可以一直相互交换。如注释中所述,您应该使用示例数组手动尝试代码,或者使用示例数组检查代码运行情况。请参阅下面的示例数组
您可能希望将while(true)
循环切换为递归调用,以使代码更清晰。此外,您还可以在my上练习快速排序的不同步骤
假设数组={3,1,2,3},轴是3。什么都不会改变,代码将永远循环
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){ //this will just swap the 3's with each other.
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
}
else{
return higher;
}
}
while(true){
int pivot=array[lower];
while(阵列[下]枢轴)
更高--;
if(Lower)您的拆分函数对输入[1、2、3]有何作用?是否确定?编写测试或在调试器中查看它(或两者都有)。减少你的代码:去掉所有已经有效的东西,这不是你问题的一部分,只保留运行快速排序的代码。你的按键正在注册吗?然后只编写一个小程序,只调用你的快速排序算法,并显示其中断的位置。[查看我对这个问题的回答。它解释了快速排序代码][1][1]:那么如何阻止这两个3(正如您在示例中提到的)相互交换呢?很抱歉,我的编程时间不长。您需要弄清楚(或用谷歌搜索它:)作为一个开始,请注意,您的第一个内部while循环在while(数组[lower]下)时不执行任何操作while
int[] Array={1,41,2,90,32,65,12,43,78,65,46,67};
while(true){
int pivot=array[lower];
while(array[lower]<pivot)
lower++;
while(array[higher]>pivot)
higher--;
if(lower<higher){ //this will just swap the 3's with each other.
int temp=array[higher];
array[higher]=array[lower];
array[lower]=temp;
}
else{
return higher;
}
}