快速排序(QuickSort)

第一次实际实现快速排序。。。,

虽然之前理解其思想方法,但编程实现过程中仍出现了很多问题

比如,区分一次快排和递归实现整体排序;递归时要注意递归终止条件(low<high);最终函数QuickSortAll的编写。

#include "stdafx.h"
#include <iostream>

using namespace std;

//快速排序(QSort+QuickSort)

//一次快排
int QSort(int* list, int low,int high)
{
    int SepValue = list[low];
    while(low < high)
    {
        while(low < high && SepValue <= list[high])
            high--;
        list[low] = list[high];

        while(low < high && SepValue >= list[low])
            low++;
        list[high] = list[low];
    }
    if(low == high)
        list[low] = SepValue;

    return low;
}

//递归实现快速排序
//千万记住:检查递归的终止条件!!!
void QuickSort(int* list, int low, int high)
{
    if(low < high)  //相当于递归终止条件
    {
        int SepLocation = QSort(list, low, high);

        if(SepLocation > low)
            QuickSort(list, low, SepLocation-1);
        if(SepLocation < high)
          QuickSort(list, SepLocation+1, high);
    }
}

void QuickSortAll(int* list, int listlength)
{
    if(list == NULL)
        return;
    QuickSort(list, 0, listlength-1);
}


int main()
{
    int list[] = {3,5,1,3,9,2};
    QuickSortAll(list,6);

    for(int i=0; i<6; i++)
        cout<<list[i]<<' ';
    cout<<endl;
    return 0;
}

 经过整理后的快速排序如下:(QuickSort)

说明:以后涉及到快速排序时,就用该代码了!!!

//QuickSort实现从大到小排序
//一次快排+递归
//一次快排
int Partition(int* list, int start, int end)
{
    if(start >= end)
        throw new exception("Invalid paraterments");

    int SepValue = list[start];
    while(start < end)
    {
        while(start < end && list[end] <= SepValue)  //每个start < end都是必要的
            end--;
        list[start] = list[end];

        while(start < end && list[start] >= SepValue)   //每个start < end都是必要的
            start++;
        list[end] = list[start];
    }

    if(start == end)
        list[start] = SepValue;

    return start;
}

//递归排序QuickSort
void QuickSort(int* list, int length, int start, int end)
{
    if(list == NULL || start < 0 || end >= length)
        return;
    if(start < end)
    {
        int SepLocation = Partition(list, start, end);
        if(SepLocation > start)
            QuickSort(list,length,start,SepLocation-1);
        if(SepLocation < end)
            QuickSort(list,length,SepLocation+1,end);
    }
}

int main()
{
    const int length = 6;
    int list[length] = {1,2,3,4,5,6};
    QuickSort(list,length,0,length-1);

    for(int i=0; i<length; i++)
        cout<<list[i]<<' ';
    cout<<endl;
    return 0;
}

快速排序由两部分代码组成:

1,主部分:void QuickSort(int* list, int length, int start, int end);

2,内含部分:int Partition(int* list, int start, int end);

调用时,QuickSort(list,length,0,length-1);

清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
原文地址:https://www.cnblogs.com/hello-yz/p/3246163.html