快排的改进

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int selectPartition(vector<int>& arr, int low, int high)
{
    int mid = low + ((high - low) >> 1);
    if (arr[mid] > arr[high])
    {
        swap(arr[mid], arr[high]);
    }
    if (arr[low] > arr[high])
    {
        swap(arr[low], arr[high]);
    }
    // low的位置上保存三个位置的中间值
    if (arr[mid] > arr[low])
    {
        swap(arr[mid], arr[low]);
    }

}

int partition(vector<int>& a, int low, int high)
{
    selectPartition(a, low, high);
    int pivot = a[low];
    // int pivot = a[low];

    while (low < high)
    {
        while (low < high && a[high] >= pivot) high--;
        a[low] = a[high];
        while (low < high && a[low] <= pivot) low++;
        a[high] = a[low];
    }
    a[low] = pivot;
    return low;
}

void Qsort(vector<int>& a, int low, int high)
{
    int pivotloc;
    if (low < high)
    {
        pivotloc = partition(a, low, high);
        Qsort(a, low, pivotloc - 1);
        Qsort(a, pivotloc + 1, high);
    }
}

void QuickSort(vector<int>& a, int low, int high)
{
    Qsort(a, low, high - 1);   
}

int main()
{
    vector<int> a = {1, -2, 3, 55, -23, 0, -23, 44, 2, 55, 99, 23, -40};
    QuickSort(a, 0, a.size());
    for(auto e : a)
    {
        cout << e << " ";
    }
    cout << endl;
    return 0;
}

https://blog.csdn.net/hacker00011000/article/details/52176100

上一篇:冒泡排序快速排序C语言


下一篇:JZ42 和为S的两个数字