[英]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.