快速排序

快速排序

原理

    和之前學習到的歸併排序一樣,快速排序也使用了分治的思想。假設現有一個數組a[start,end],對這個數組進行快速排序分了下面三個步驟:

  1. 分解:在數組a[start,end]中確定一個標準(一般是找a[end]),以這個標準調整元素並找出一個位置p,使得start<=i<=p-1區域內的所有元素都小於等於a[end],而p+1<=i<=end這個區域中所有元素都大於等於a[end]。下面是圖解:
    這裏寫圖片描述
  2. 解決:通過遞歸調用快速排序,對分出來的子數組a[start,p-1]和a[p+1,end]進行排序。
  3. 合併:因爲子數組都是原址排序的,因此不需要合併的操作。

C語言實現

int partition(int* a, int start, int end)
{
    int x = a[end];
    int i = start;
    //調整整個數組中元素的位置並找出中間值的索引
    for (int j = start; j < end; j++)
    {
        if (a[j] <= x)
        {
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
            i++;
        }
    }
    //將中間值放在找出的中間值索引處
    int t = a[i];
    a[i] = a[end];
    a[end] = t;
    return i;
}

void quick_sort(int* a, int from, int to)
{
    if (from < to)
    {
        int p = partition(a, from, to);
        quick_sort(a, from, p - 1);
        quick_sort(a, p + 1, to);
    }
}

void main()
{
    int count, *p;
    printf("請輸入需要排序的數的個數 :");
    scanf_s("%d", &count);
    p = (int*)malloc(count * 2);
    printf("\n請輸入需要排序的%d個數字:",count);
    for (int i = 0; i < count; i++)
    {
        scanf_s("%d", p+i);
    }
    printf("\n快速排序後的數組:");

    quick_sort(p, 0, count - 1);
    for (int i = 0; i < count; i++)
    {
        printf("%d ", p[i]);
    }
    printf("\n");
    system("pause");
}

算法分析

    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章