zoukankan      html  css  js  c++  java
  • 快速排序算法递归和非递归实现

    /********************************
     * 快速排序算法
     * 
     *********************************/
    
    #include <stdio.h>
    
    /******************************
     * 一次划分算法
     * pList    需要排序的数组
     * nLow     起始位置
     * nHigh    结束位置
     *****************************/
    int Partiton(int *pList,int nLow,int nHigh)
    {
        int nTmp = pList[nLow];
        
        while(nLow < nHigh)
        {
            while(nLow < nHigh && nTmp <= pList[nHigh])
            {
                nHigh--;
            }
            pList[nLow] = pList[nHigh];
            while(nLow < nHigh && nTmp >= pList[nLow])
            {
                nLow++;
            }
            pList[nHigh] = pList[nLow];
        }
        pList[nLow] = nTmp;
        
        return nLow;
    }
    /**************************
     * 使用Partition进行快速排序
     * 
     * 递归实现
     **************************/
    void QuickSort(int *pList,int nLow, int nHigh)
    {
        int nPivotLoc;
        if(nLow < nHigh)
        {
            nPivotLoc = Partiton(pList, nLow, nHigh);
            QuickSort(pList, nLow, nPivotLoc - 1);
            QuickSort(pList, nPivotLoc + 1, nHigh);
        }
    }
    
    /******************************
     * 
     * 非递归实现
     * 
     ******************************/
    void Sort(int *pList, int nLow, int nHigh)
    {
        int *pPosArr = (int *)malloc((nHigh - nLow + 1)*sizeof(int));
        int nPos = 0;
        int nTmpLow;
        int nTmpHigh;
        int nPivotLoc;
        
        pPosArr[nPos++] = nLow;
        pPosArr[nPos++] = nHigh;
        while(nPos > 0)
        {
            nTmpHigh = pPosArr[--nPos];
            nTmpLow = pPosArr[--nPos];
            if(nTmpLow >= nTmpHigh)
            {
                break;
            }
            nPivotLoc = Partiton(pList, nTmpLow, nTmpHigh);
            if(nPivotLoc - 1 > nTmpLow)
            {
                pPosArr[nPos++] = nLow;
                pPosArr[nPos++] = nPivotLoc - 1;
            }
            if(nPivotLoc + 1 < nTmpHigh)
            {
                pPosArr[nPos++] = nPivotLoc + 1;
                pPosArr[nPos++] = nHigh;
            }
        }
        free(pPosArr);
    }
    
    /******************************
     * 测试函数
     * 
     *****************************/
    int main(void)
    {
        int nList[] = {49, 38, 65, 97, 76, 13, 27, 49};
        int i;
        
        Sort(nList,0,sizeof(nList)/sizeof(int) - 1);
        
        for(i = 0; i < 8; i++)
        {
            printf("%d  ",nList[i]);
        }
        putchar('\n');
        return 0;
    }
  • 相关阅读:
    nginx rewrite 伪静态重写学习笔记
    正则表达式相关知识
    rpm的含义
    find命令的使用
    chmod的运用方式
    [GO]数组的比较和赋值
    [GO]二维数组的介绍
    [GO]变量内存和变量地址
    [GO]给导入包起别名
    阿里云负载均衡SLB 七层https协议 nginx 获取真实IP
  • 原文地址:https://www.cnblogs.com/chunxi/p/3035824.html
Copyright © 2011-2022 走看看