快速排序

#include
#include 

using namespace std;

int partition(vector<int>& v, int low, int high)
{
    int pivot = v[high];
    int i = low - 1;
    for (int j = low; j < high; ++j)
    {
        if (v[j] < pivot)
        {
            i++;
            swap(v[i], v[j]);
        }
    }
    swap(v[i + 1], v[high]);
    return i + 1;
}

void quickSort(vector<int>& v, int low, int high)
{
    if (low < high)
    {
        int mid = partition(v, low, high);

        quickSort(v, low, mid - 1);
        quickSort(v, mid + 1, high);
    }
}

void qSort(vector<int>& v)
{
    quickSort(v, 0, v.size() - 1);
}

int main(void)
{
    int a[] = { 3, 5, 7, 9, 2, 3, 1, 0, 7, 5, 4 };
    vector<int> v(a, a+11);

    cout << "原来顺序:" << endl;
    for (auto x : v)cout << x << " ";
    cout << endl;

    qSort(v);

    cout << "快速排序之后:" << endl;
    for (auto x : v)cout << x << " ";
    cout << endl;

    system("pause");
    return 0;
}

你可能感兴趣的:(算法)