快速排序

这里介绍快速排序的两种写法,其中第二种方法更通用,其中的partition方法更是在很多地方可以应用。
快速排序是一个递归的过程,每次都是将需要排序的序列分为两个部分。
第一种写法:

public void quickSort(int[] arr,int left,int right) {

        if(left >= right)//递归结束条件
            return;
        int i = left,j = right;
        int standard = arr[left];//第一个元素为枢轴
        while(i < j) {
            while(i < j && arr[j] >= standard) {
                j--;
            }
            if(i < j)
                arr[i] = arr[j];

            while(i < j && arr[i] <= standard) {
                i++;
            }
            if(i < j)
                arr[j] = arr[i];
        }
        arr[i] = standard;
        quickSort(arr,left,i-1);//递归左半部分
        quickSort(arr,i+1,right);//递归右半部分
    }

第二种写法:

//使用partition函数的快排
public void quickSortByPartition(int[] arr, int start, int end) {
    if(start >= end)
        return;
    //一分为二之后,返回分界点
    int index = partition(arr, start, end);
    if(index > start)
        quickSortByPartition(arr, start, index-1);
    if(index < end)
        quickSortByPartition(arr, index+1, end);
}

//获取一个随机枢轴,将数组一分为二,返回分界点index
public int partition(int[] arr, int start, int end) {

    int r = (int)(start + Math.random()*(end-start+1));
    swap(arr, r, end);
    int index = start;
    for(int i = start;iif(arr[i] <= arr[end]) {
            if(i != index)
                swap(arr, i ,index);
            index++;
        }
    }
    swap(arr, index, end);
    return index;
}

public void swap(int[] a, int i, int j) {
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
}

其中的partition函数可以在O(n)时间找到数组中第任意大的数。

你可能感兴趣的:(基础算法)