纪念逝去的岁月——C/C++快速排序

快速排序

代码

#include <stdio.h>

void printList(int iList[], int iLen)
{
    int i = 0;
    for(i = 0; i < iLen; i++)
    {
        printf("%d ", iList[i]);
    }
    printf("\n");
}

void printList(int iList[], int iBegin, int iEnd)
{
    int i = 0;
    for(i = 0; i < iBegin; i++)
    {
        printf("%c ", '_');
    }
    for(i = iBegin; i < iEnd; i++)
    {
        printf("%d ", iList[i]);
    }
    printf("\n");
}

int _quickSort(int iList[], int iLeft, int iRight)
{
    if(iLeft >= iRight)
    {
        return 0;
    }
    int i = iLeft, j = iRight;
    int t = iList[i];
    printf("%d<->%d mid(%d) : ", i, j, t);
    while(i < j)
    {
        while(t < iList[j] && j > i)
        {
            j--;
        }
        if(j > i)
        {
            iList[i] = iList[j];
            i++;
        }

        while(t >= iList[i] && i < j)
        {
            i++;
        }
        if(i < j)
        {
            iList[j] = iList[i];
            j--;
        }
    }
    iList[i] = t;
    printList(iList, 10);
    _quickSort(iList, iLeft, i - 1);
    _quickSort(iList, i + 1, iRight);

    return 0;
}

int Quick(int iList[], int iLen)
{
    _quickSort(iList, 0, iLen - 1);
    return 0;
}

int main()
{
    int iNum = 10;
    int iList[10] = {6, 7, 5, 9, 0, 1, 2, 4, 3, 8};
    printf("src : ");
    printList(iList, iNum);
    putchar('\n');
    Quick(iList, iNum);
    putchar('\n');
    printf("dst : ");
    printList(iList, iNum);

    return 0;
}

编译

$ g++ -g -o quickSort quickSort.cpp

运行

$ ./quickSort 
src : 6 7 5 9 0 1 2 4 3 8 

0<->9 mid(6) : 3 4 5 2 0 1 6 9 7 8 
0<->5 mid(3) : 1 0 2 3 5 4 6 9 7 8 
0<->2 mid(1) : 0 1 2 3 5 4 6 9 7 8 
4<->5 mid(5) : 0 1 2 3 4 5 6 9 7 8 
7<->9 mid(9) : 0 1 2 3 4 5 6 8 7 9 
7<->8 mid(8) : 0 1 2 3 4 5 6 7 8 9 

dst : 0 1 2 3 4 5 6 7 8 9

再见……

 

posted @ 2015-03-12 09:51  fengbohello  阅读(261)  评论(0编辑  收藏  举报