快速排序

package com.test;
public class quickSort {
             
    public quickSort() {
                 
    }
             
    public int getMiddle(int[] list, int low, int high) {
        int temp = list[low];
        while(low < high) {
            while(low < high && list[high] >= temp ) {
                high--;
            }
            list[low] = list[high];
            while(low < high && list[low] <= temp) {
                low++;
            }
            list[high] = list[low];
        }
        list[low] = temp;
        return low;
    }
    public void quick(int[] list, int low, int high) {
        if(low < high) {
            int middle = this.getMiddle(list, low, high);
            quick(list, low, middle-1);
            quick(list, middle+1, high);
        }
    }
}

測試方法

public static void main(String[] args) {
        int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99,
                98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 };
        quickSort q = new quickSort();
        q.quick(a, 0, a.length - 1);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章