Java教程

快排的改进

本文主要是介绍快排的改进,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#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

这篇关于快排的改进的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!