[英]Quicksort IndexOutOfBounds
我參加了一些編程課程,並且想知道我是否可以在我的Quicksort Algorithm項目上獲得幫助。
這是我想出的代碼:
public class QuickSort {
public static void main(String[] args)
{
int array [] = {12, 25, 17, 19, 51, 32, 45, 18, 22, 37, 15};
quickSorting(array);
System.out.printf("The sorted array is: ", array);
}
public static void quickSorting(int array[])
{
int pivot = array[0];
int i = pivot + 1;
int j = array.length;
while(i >= j)
{
while(array[i] <= pivot)
i++;
while(array[j] >= pivot)
j--;
swapValues(array[i] , array[j]);
}
swapValues(array[i] , array[j]);
swapValues(array[pivot], array[j]);
}
public static void swapValues(int a, int b)
{
int temporary = a;
a = b;
b = temporary;
}
}
我一直在獲取數組錯誤。
這是問題所在:
int pivot = array[0];
int i = pivot + 1;
array [0] = 12 => i = 13;
現在, while(array[i] < pivot)
=> [i]不能為13。
您可能意味着pivot = 0;
, array[0]
表示取值,這是錯誤的。
首先,交換函數是通過值而不是引用來調用的。 因此,數組中的實際元素不會交換。 請將該實現更改為類似
public static void swap(int array[], int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
接下來,如果數組已經排序,請檢查“ i”和“ j”的邊界是否正確。
我認為這應該可以解決問題。
正如Parth指出的那樣,您錯過了將其放回陣列的過程。 您交換了它,但是如果您的數組沒有反映出來,那又有什么用呢?
如果原始數組是Objects數組而不是原始類型(Example Integer []),則對您來說效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.