QuickSort

来源:互联网 发布:华为帐号无法获取数据 编辑:程序博客网 时间:2024/06/07 02:34


      虽说数据结构和编程语言关系不大,但是要实现还是蛮。。。

     

public class Main {    /**  快速排序  */    /**  快速排序要做的就是找到那么个支点,使得支点左边的数始终比支点小,右边的数始终比支点大*/    public static void QuickSort(int[] list) {        QSort(list, 0, list.length - 1);    }    public static void QSort(int[] list, int low, int height) {        /** 递归直至完成排序*/        if (low < height) {            int pivot = partition(list, low, height);//得到一个支点            QSort(list, 0, pivot - 1);/** 对支点左边的数据进行排序 */            QSort(list, pivot + 1, height);/** 对支点右边的数据进行排序 */        }    }    public static int partition(int[] list, int low, int height) {        int pivotkey = list[low];        while (low < height) {            /** 使得支点右边的数要比支点大 */            while (low < height && list[height] >= pivotkey) {                height--;//让右边数据依次和支点比较,            }            swap(list, low, height);//交换            while (low < height && list[low] <= pivotkey) {                low++;            }            swap(list, low, height);        }        return low;    }    public static void swap(int[] list, int low, int height) {        int temp = list[low];        list[low] = list[height];        list[height] = temp;    }    public static void main(String[] args) {//      System.out.println("HelloWorld.");        int[] a = {10, 32, 1, 9, 5, 7, 12, 0, 4, 3};        StringBuffer sb = new StringBuffer();        QuickSort(a);        for (int i = 0; i < a.length; i++) {            sb.append(a[i]+" ");        }        System.out.println(sb);    }}

0 0
原创粉丝点击