QuickSort

来源:互联网 发布:手机淘宝联盟怎么用 编辑:程序博客网 时间:2024/06/15 17:51

不需要额外空间的快速排序

public class QuickSort {    public static void quickSort(int[] arr, int low, int high) {        int privot;        if(low < high) {            privot = Partition(arr, low, high);            quickSort(arr, low, privot-1);            quickSort(arr, privot+1, high);        }    }    private static int Partition(int[] arr, int low, int high) {        if(arr == null) throw new NullPointerException();        else if(low < 0 || high >= arr.length) throw new ArrayIndexOutOfBoundsException();        int privotkey = arr[low];        while (low < high) {            while (low < high && arr[high] >= privotkey) {                high--;            }            swap(arr, low, high);            while (low < high && arr[low] < privotkey) {                low++;            }            swap(arr, low, high);        }        return low;    }    private static void swap(int arr[], int i, int j) {        int tmp = arr[i];        arr[i] = arr[j];        arr[j] = tmp;    }    public static void main(String[] args) {        int ans[] = {1 , 2, 3, 4 ,5 , 10 , 9 , 8, 7, 6};        QuickSort.quickSort(ans, 0, ans.length-1);        for(int i = 0; i < ans.length; ++i) System.out.println(ans[i] + " ");    }}
原创粉丝点击