快速排序算法递归和非递归实现
/******************************** * 快速排序算法 * *********************************/ #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; }