_在路上

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/************************************************************************/
/* 冒泡排序:又叫简单交换排序,冒泡,顾名思义,实际上总是将要扫描到的   */
/* 最大/小的元素值推到尾部  */
/************************************************************************/
void swapSort (int *d, int len)
{
    int i, j, t, IsEnd = 1;
    
    for (i = 0; IsEnd && i < len - 1; i++)              /* 冒泡n-1次即可 */
    {
        for (IsEnd = 0, j = 1; j < len - i; j++)        /* 起始位置不变,每趟冒泡扫描的元素会原来越少 */
        {
            /* 顺序排列,交换序列 */
            if (d[j - 1] > d[j])
            {
                t        = d[j];
                d[j]     = d[j - 1];
                d[j - 1] = t;

                IsEnd    = 1;                           /* 如果某一次冒泡从没交换过,则退出排序 */
            }
        }
    }
}


/************************************************************************/
/* 快速交换排序:以起始下标元素为分界线,做一趟快速排序,分成两个子表。 */
/* 注意参数high 是最后一个有效下标。                                    */
/************************************************************************/
int quickSubSort (int * d, int low, int high)
{
    int x     = d[low];                             /* d[low] 是多余空间 */

    while (low < high)
    {
        while (low < high && d[high] >= x)
            --high;

        if (low < high)
        {
            d[low++] = d[high];                     /* d[high] 是多余空间 */
        }

        while (low < high && d[low] < x)
            ++low;

        if (low < high)
        {
            d[high--] = d[low];                     /* d[low] 是多余空间 */
        }
    }
    
    d[low] = x;                                     /* low == high,填充分界左右子表的基准元素 */

    return low;
}

/* 注意参数low和high表示有效的头尾下标 */
void quickSort (int * d, int low, int high)
{
    int pos;

    if (low < high)
    {
        pos = quickSubSort(d, low, high);           /* 一趟快速交换排序,以头元素为基准分界元素,划分左右子表 */
        quickSort(d, low, pos - 1);                 /* 对左子表快速排序 */
        quickSort(d, pos + 1, high);                /* 对右子表快速排序 */
    }
}


void Swap_Example (void) 
{
    int i;
    int arr[7] = {10, 7, 11, 12, 9, 21, 6};
    
    quickSort(arr, 0, 6);   //swapSort(arr, 7);

    for (i = 0; i < 7; i++)
        printf("%4d", arr[i]);
    puts("\r\n");
}


int main ()
{
    Swap_Example();

    return 0;
}
posted on 2012-10-09 10:54  _在路上  阅读(210)  评论(0编辑  收藏  举报