我不知道为什么,但只有我的中间元素仍未分类

时间:2016-11-07 17:34:35

标签: java arrays quicksort

由于某种原因,我的数组的中间元素仍未排序......

public class QuickSort {

    public int a[];

    public QuickSort(int[] a) {
        this.a = a;
    }

    private void swap(int pos1, int pos2) {
        int t = a[pos1];
        a[pos1] = a[pos2];
        a[pos2] = t;
    }

    private int partition(int low, int high) {
        int i = low, j = low + 1, pivot = low;
        while (j < high) {
            if (a[j] <= a[pivot]) {
                swap(++i, j);
            }
            j++;
        }
        swap(i, pivot);
        return i;
    }

    private void sort(int low, int high) {
        int i;
        if (low >= high)
            return;
        else {
            i = partition(low, high);
            sort(i + 1, high);
            sort(low, i - 1);
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder("");
        for (int i : a) {
            sb.append(i);
            sb.append("\n");
        }

        return sb.toString();
    }

    private static int[] generateRandomNumbers(int s) {

        int a[] = new int[s];

        for (int i = 0; i < s; i++) {
            a[i] = new Random().nextInt(50);
        }

        return a;
    }

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of elements");
        int s = sc.nextInt();

        QuickSort obj = new QuickSort(generateRandomNumbers(s));

        System.out.println(obj.toString());

        obj.sort(0, s - 1);

        System.out.println("\n");
        System.out.println(obj.toString());
    }

}

阵列中填充了随机生成的数字,这是一种标准的快速排序算法 任何帮助将不胜感激,我是一个新手程序员,并试图调试此代码太长时间...

3 个答案:

答案 0 :(得分:0)

修改

swap(i+1, pivot);
return i+1;

int i = low-1, j = low, pivot = high;

if (low < high)
        {
            i = partition(low, high);
            sort(i + 1, high);
            sort(low, i - 1);
        }

在这些变化之后完美无瑕地工作。

答案 1 :(得分:0)

或者只是更改'&lt;'到'&lt; =',因为它没有检查高元素......

 while (j <= high) {

答案 2 :(得分:0)

我发现了我的错误...... 应该是

 while (j <= high)

而不是

(j < high)