在java中实现QuickSort的一些问题

时间:2011-05-18 01:42:53

标签: java quicksort sorting

这是我的代码:

public class Main
{
    public static void main(String[] args)
    {
        int[] temp = {4,2,6,4,5,2,9,7,11,0,-1,4,-5};
        quickSort(temp);
        for(int s : temp) System.out.println(s);
    }

    public static void quickSort(int[] data)
    {
        quickSort(data, 0, data.length);
    }

    public static void quickSort(int[] data, int first, int n)
    {
        int p, n1, n2;
        if(n > 1)
        {
            p = partition(data, first, n);
            n1 = p - first;
            n2 = n - n1 - 1;
            quickSort(data, first, n1);
            quickSort(data, p+1, n2);
        }
    }

    private static int partition(int[] A, int first, int n )
    {
        int right = first + n - 1;
        int ls = first;
        int pivot = A[first];
        for(int i = first+1; i <= right; i++)
        {
            if(A[i] <= pivot)
            // Move items smaller than pivot only, to location that would be at left of pivot
            {
                ls++;
                swap(A[i], A[ls]);
            }
        }
        swap(A[first], A[ls]);
        return ls;
    }

    private static void swap(int i, int j)
    {
        int temp = i;
        i = j;
        j = temp;
    }
}

运行此程序后,它不会对数组进行排序并打印相同的数组而不进行排序。

4
2
6
4
5
2
9
7
11
0
-1
4
-5

此实施中有什么问题?

2 个答案:

答案 0 :(得分:9)

问题是你的swap()函数实际上没有交换数组中的元素,它只是将值交换为两个整数变量。整数在Java中按值传递,而不是通过引用传递。

将此替换为重新分配数组值的交换函数,例如:

private static void swap(int[] array, int pos1, int pos2) {
    int temp = array[pos1];
    array[pos1] = array[pos2];
    array[pos2] = temp;
}

答案 1 :(得分:1)

您的交换函数按值传递其参数。 Everthing是java中的pass-by-value。

您的交换功能需要通过引用有效传递:请参阅上面的@matt b的答案。

有关参数传递的详细说明,请参阅Is Java pass by reference?