排序算法——快速排序

蓝咒 提交于 2019-11-27 08:32:16

图示思想:

 

int Partition(int* a, int low, int high)
{
    int pivotkey = a[low];
    while (low < high)
    {
        while (low < high && a[high] >= pivotkey)
            high--;
        a[low] = a[high];
        while (low < high && a[low] <= pivotkey)
            low++;
        a[high] = a[low];
    }
    a[low] = pivotkey;
    return low;
}
void QuickSort(int* a, int low, int high)
{
    if (low < high)
    {
        int pivotloc = Partition(a, low, high);
        QuickSort(a, low, pivotloc-1);
        QuickSort(a, pivotloc+1, high);
    }
}

int main()
{
    int arr[] = { 9,2,3,1,5,4,7,8,6 };
    int n = sizeof(arr) / sizeof(int);

    int low = 0, high = n - 1;
    QuickSort(arr, low,high);


    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!