荷蘭國旗優化快速排序

#include<iostream>
#include<cstdio>
using namespace std;
int p1, p2;

void swap(int a[], int x, int y)
{
    int temp = a[x];
    a[x] = a[y];
    a[y] = temp;
}

void partition(int a[], int l, int r)
{
    int less = l - 1;
    int more = r;
    while(l < more)
    {
        if(a[l] < a[r])
        {
            swap(a, ++less, l++);
        }
        else if(a[l] > a[r])
        {
            swap(a, --more, l);
        }
        else
        {
            l++;
        }
    }
    swap(a, more, r);
    p1 = less + 1;
    p2 = more;
}

void quickSort(int a[], int l, int r)
{
    if(l < r)
    {
        partition(a, l, r);
        quickSort(a, l, p1 - 1);
        quickSort(a, p2 + 1, r);
    }
}

int main()
{
    int a[7] = {8, 7, 3, 9, 2, 0, 6};
    quickSort(a, 0, 6);
    for(int i = 0; i < 7; i++)
    {
        cout << a[i] << " ";
    }

}

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