Java 快速排序索引自动边界
我参加了一些编程课程,我想知道我的快速排序算法项目是否能得到帮助 下面是我想出的代码:Java 快速排序索引自动边界,java,algorithm,Java,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.prin
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;
数组[0]=12=>i=13
现在,whilearay[i]您可能是指pivot=0,数组[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所指出的,
你没能把它放回阵列。你交换了它,但是如果你的数组没有反映出来,那有什么意义呢
如果您的原始数组是一个对象数组,而不是原始类型示例Integer[],那么它对您来说会很好。@Kevin Java System.out.printf非常独特。@greybeard,这实际上是我发布线程时犯的一个错误。我不知道如何返回并更改它。int j=array.length;-这不应该是array.length-1吗?我将其添加到代码中,但我仍然不断将索引超出范围。我认为您的条件是反向的。难道不是我吗