快速排序算法(Quicksort)


快速排序算法是對集合中元素進行排序最通用的算法,俗稱快排,其算法的時間復雜度為O(nlgn),空間復雜度為O(1)。

我們舉例來對其算法思路進行理解,譬如數組 A = { 4, 8, 1, 2, 9, 7, 3, 0, 5, 6 };

第一步,以最后一個數6為基准,把小於等於6的數挪到數組左邊,把大於6的數挪到數組右邊。

那么結果為 { 4, 1, 2, 3, 0, 5, 8, 9, 7, 6 },這個時候再做一步,把8和6進行交換,得到{ 4, 1, 2, 3, 0, 5, 6, 9, 7, 8 }把6的最新位置返回。這個時候其實數組被切割成兩部分,准確地說,是三部分{ 4, 1, 2, 3, 0, 5 }, { 6 }和{ 9, 7, 8 }.

第二步,對 { 4, 1, 2, 3, 0, 5 }和 { 9, 7, 8 }重復第一步的過程,我們得到

{ 4, 1, 2, 3, 0 }, { 5 }, { 7 }, { 8 }, { 9 }

第三步,再對{ 4, 1, 2, 3, 0 }進行分割,得到 { 0 }, { 1, 2, 3, 4 }

第四步,再對{ 1, 2, 3, 4 }進行分割,得到{ 1, 2, 3 }和{ 4 }

第五步,對{ 1, 2, 3 }進行分割,得到{ 1, 2 }和{ 3 }

第六步,對{ 1, 2 }進行分割,得到{ 1 }和{ 2 }

C實現代碼如下

#include <stdio.h>

#define LEN 10

int partition(int *arr, int start, int end)
{
    int pivot = arr[end];
    int i = start;
    int j;
    int tmp;
    for (j = start; j < end; ++j) {
        if (arr[j] <= pivot) {
            tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
            ++i;
        }
    }
    arr[end] = arr[i];
    arr[i] = pivot;
    return i;
}

int quicksort(int *arr, int start, int end)
{
    int pivot_location;
    if (start < end) {
        pivot_location = partition(arr, start, end);
        quicksort(arr, start, pivot_location - 1);
        quicksort(arr, pivot_location + 1, end);
    }
}

int main()
{
    int i;
    int arr[LEN] = { 4, 8, 1, 2, 9, 7, 3, 0, 5, 6 };
    quicksort(arr, 0, LEN - 1);
    for (i = 0; i < LEN; ++i)
        printf("%d\n", arr[i]);
    return 0;
}

 

Java實現代碼如下

public class QuickSort {

    // Sort a list of numbers in an array within [start, end]
    public void quickSort(int[] A, int start, int end) {
        if (start < end) {
            int pivotLocation = partition(A, start, end);
            quickSort(A, start, pivotLocation - 1);
            quickSort(A, pivotLocation + 1, end);
        }
    }
    
    // Select A[end] as the pivot, separate the array into two parts.
    private int partition(int[] A, int start, int end) {
        int pivot = A[end];
        int i = start;
        for (int j = start; j < end; ++j) {
            if (A[j] <= pivot) {
                int tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
                ++i;
            }
        }
        
        A[end] = A[i];
        A[i] = pivot;
        return i;
    }
    
    public static void main(String[] args) {
        QuickSort q = new QuickSort();
        int[] A = { 4, 8, 1, 2, 9, 7, 3, 0, 5, 6 };
        q.quickSort(A, 0, A.length - 1);
        for (int i = 0; i < A.length; ++i) {
            System.out.println(A[i]);
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM