使用快速排序作为整数数组时的分区方法

时间:2015-05-13 10:48:55

标签: java sorting quicksort partition

我希望能够使用QuickSort算法对整数数组进行排序,但是我的分区方法出现问题并使用了数据透视表。这是我的代码,底部有一个测试方法。

public class QuickSort {

public static  void sort(int [] table) {
   quickSort(table, 0, table.length - 1);
}

private static void quickSort(int [] table,int first,int last) {

    printArray(table);

    if (first < last) {

        int pivIndex = partition(table, first, last);

        System.out.println("pivindex = "+pivIndex);
        quickSort(table, first, pivIndex - 1);


        quickSort(table, pivIndex + 1, last);
    }
}

private static void bubbleSort(int[] table,int first,int last)
{

 int middle = (first + last) / 2;


    if (table[first]>table[middle]) {

        swap(table,first,middle);
    }

 if (table[middle]>table[last]) {

        swap(table,middle,last);
    }

    if (table[middle]<table[first]) {

        swap(table,first,middle);
    }

  swap(table,first,middle);
}

private static int partition(int[] table,int first,int last) {

    bubbleSort(table, first, last);

    Integer pivot = table[0];

    int start = first;
    int end = last;
    while(start<end)
    {
        while((start<last)&&table[start]<=pivot)
        {start++;
        }

        while(table[end]>pivot)
        {
                end--;
        }

        if(start<end)
        {
            swap(table, start, end);

        }
    }
    printArray(table);
    swap(table, first, end);

    return end;        
}
private static  void swap(int [] table, int i, int j) {
    int temp = table[i];
    table[i] = table[j];
    table[j] = temp;
}
private static  void printArray(int [] array) {
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i]);

        if (i < (array.length + 1)) {
            System.out.print(" ");
        }
    }
    System.out.println();
}

public static void main(String[] args) {
    int [] array =  {42,37,45,70,12,19, 39, 43, 61,7,99};
    sort(array);
}

}

0 个答案:

没有答案