交换排序(快速排序)

#include <iostream>
using namespace std;

int Partition(int a[], int p1, int p2)
{
    int temp = a[p1];

    while (p1 < p2)
    {
        while (p1 < p2 && a[p2] > temp) p2--;
        a[p1] = a[p2];

        while (p1 < p2 && a[p1] < temp) p1++;
        a[p2] = a[p1];

    }

    a[p1] = temp;

    return p1;
}

void QuickSort(int a[], int left, int right)
{
    int temp = 0;
    if (right > left)
    {
        temp = Partition(a, left, right);

        QuickSort(a, left, temp - 1);
        QuickSort(a, temp + 1, right);        
    }
}

// 在纸上比划,容易理解多了;
int main()
{
    int a[] = {9,3,2,5,6,4,8,1};

    int size = sizeof(a)/sizeof(int);

    for (int i = 0; i < size; ++i)
    {
        cout << a[i] << endl;
    }

    cout << endl;

    QuickSort(a, 0, size - 1);

    for (int i = 0; i < size; ++i)
    {
        cout << a[i] << endl;
    }

}

 

posted @ 2013-01-11 04:20  rookieeeeee  阅读(194)  评论(0编辑  收藏  举报