排序算法 Sorting Algorithm(二)

算法课老师在讲分治时的一个例子,还提到了其他很多经典算法,这周统一总结一下。
– 快速排序(QUICK-SORT)

QUICK-SORT(A, p, r)
    if p<r
        then q <-PATITION(A, p, r)
        QUICK-SORT(A, p, q)
        QUICK-SORT(A, q+1, r)

QUICK-SORT (A, n)

PARTITION(A, p ,r)
    if r < p 
        then return -1;
    if r = p
        then return r 
    x<-A[p]
    i<-p+1
    j<-r
    while i<j
        do  if A[i]<x
                then i++; 
            if A[j]>x
                then j--;
            if i<j              |>即将出while循环时
                then exchange A[i]<->A[j]
    exchange A[p]<->A[i]
    return i

最坏情况:每次PARTITION找中间位置时都在最左或最右 O(n^2)
平均情况:O(nlogn)

JAVA:

public class QuickSort{
    public static void main(String[] args){
        int[] A = {1,2,5,4,3,6,9,7,8};
        System.out.println(Arrays.toString(A));  
        quickSort(A,9); 
        System.out.println(Arrays.toString(A)); 
    }
    public static void quickSort(int[] A, int n){
        if(n<=0) return;
        quickSort(A,0,n-1);
    }
    private static void quickSort(int[] A,int left, int right){

        int p = partition(A,left,right);
        quickSort(A,left,p);
        quickSort(A,p+1,right);
    }
    private static int partition(int[] A,int left,int right){
        if(left > right) return -1;
        int x = A[left];
        int i = A[left+1];
        int j = A[right];
        while(left < right){
            if(A[i] < x){
                i++;
            }
            if(A[j] > x){
                j++;
            }
            if(i < j){
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
            }
            int temp = A[i];
            A[i] = x;
            A[left] = temp;
        }
        return i;
    }
}
点赞