为什么这段代码不起作用? 以下是quicksort的递归方法。 有人还建议使用pivot take作为第一个元素的更好的分区算法吗?
import java.util.*;
class QuickSort
{
public static void callQuickSort(int[] array,int left,int right)
{
if(left<right)
{
int s = partition(array,left,right);
callQuickSort(array,left,s-1);
callQuickSort(array,s+1,right);
}
}
public static int partition(int[] array,int left,int right)
{
int pI = left; //pI = partition index
int pivot = array[right];
for(int i=left;i<=right-1;i++)
{
if(array[i] <= pivot)
{
swap(array[i],array[pI]);
pI++;
}
}
swap(array[pI],array[right]);
return pI;
}
static void swap(int a,int b)
{
int temp = a;
a = b;
b = temp;
}
public static void main(String args[])
{
int[] array = {7,2,1,6,8,5,3,4};//array declared
callQuickSort(array,0,7);
System.out.println("Sorted array is - ");
for(int i=0;i<8;i++)
System.out.print(array[i]+"\t");
}
}//end of class
输出
7 2 1 6 8 5 3 4
上面的代码返回数组而没有任何变化。为什么数组没有变化?
答案 0 :(得分:0)
在java中,数据是按值传递的,而不是通过引用传递的,所以你不能像以前那样使用swap方法。
这是工作代码:
class QuickSort {
public static void callQuickSort(int[] array, int left, int right) {
if (left < right) {
int s = partition(array, left, right);
callQuickSort(array, left, s - 1);
callQuickSort(array, s + 1, right);
}
}
public static int partition(int[] array, int left, int right) {
int pI = left; //pI = partition index
int pivot = array[right];
for (int i = left; i <= right - 1; i++) {
if (array[i] <= pivot) {
int temp = array[i];
array[i] = array[pI];
array[pI] = temp;
// swap(array[i], array[pI]);
pI++;
}
}
int temp = array[pI];
array[pI] = array[right];
array[right] = temp;
// swap(array[pI], array[right]);
return pI;
}
/*static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}*/
public static void main(String args[]) {
int[] array = {7, 2, 1, 6, 8, 5, 3, 4};//array declared
callQuickSort(array, 0, 7);
System.out.println("Sorted array is - ");
for (int i = 0; i < 8; i++)
System.out.print(array[i] + "\t");
}
}//end of class