0
我正在使用快速排序,但由於某種原因,我最終遇到了同樣的問題。 不知何故,即使我複製/粘貼應該工作的快速排序代碼,我總是會在數組中插入某個值爲0的值。快速排序問題
public class quicksort {
public int[] x;
public quicksort(int a[]){
x=a;
procedure(0, x.length-1);
}
public void procedure(int left, int right){
int index=left;
int smaller=left+1;//going to sort everything but the first element (the pivot or index)
int larger=right;
int divider=x[index];
while (smaller <= larger){
for (int z=0; z<x.length-1;z++){//display the array at each pass
System.out.print(x[z]+" ,");
}
System.out.println("|| "+smaller+" "+divider+" " +larger+" ||");
while(x[larger] > divider){ //stops at smaller then divider coming from the right
larger--;
}
while(x[smaller] < divider){//stops at bigger then divider coming from the left
smaller++;
}
if (smaller<=larger){//swaps two elements
swap(smaller, larger);
smaller++;
larger--;
}
}
index= smaller + insert(left, smaller);//moves index to its final spot in the array
//recursive call, split the array by the position of index and sort each
if (index < right-1)
procedure(index+1, right);
if (index > left+1)
procedure(left, index-1);
}
public void swap(int z, int y){//swaps values between 2 array indexes
int temp;
temp =x[z];
x[z]=x[y];
x[y]=temp;
}
public int insert(int z, int y){//inserts a value from one index to the another index in the array, adjusts array as neccessary
int it=0;
if (x[z]>x[y]){ //if values are the same => easy swap
swap(z,y);
it=0;
} else if (x[z] <= x[y]){ //if trying to insert to a bigger value
for (int f =z; f>y-1;f++) //will swap values from the position z to
swap(f, f+1); //position y (only works if z<y)
it=-1;
}
return it;
}
}
我知道,我也溢滿了遞歸調用,但首先我想找出爲什麼交換沒有采取相應的地方。那裏的輸出就是這樣,我可以看到在while循環中每次傳遞之後發生了什麼。這是一個10整數數組的示例調試。
24 ,37 ,8 ,41 ,76 ,36 ,1 ,73 ,20 ,|| 1 24 9 ||
24 ,0 ,8 ,41 ,76 ,36 ,1 ,73 ,20 ,|| 2 24 8 ||
24 ,0 ,8 ,20 ,76 ,36 ,1 ,73 ,41 ,|| 4 24 7 ||
24 ,0 ,8 ,20 ,1 ,36 ,76 ,73 ,41 ,|| 5 24 5 ||
謝謝你是的,你是對的我過於複雜,迷失在我自己的複雜情況下,當一般的想法是如此簡單。再次感謝。 – user3080877
只需簡單點,重新閱讀快速排序的主要思想,查看一些實現,然後自己完成,就這麼簡單。請記住,如果您找到有用的答案,請將其標記爲已接受。 – 3yakuya