快速排序算法 -- 非递归方式
来源:互联网 发布:世纪开元淘宝客服工资 编辑:程序博客网 时间:2024/05/16 19:27
快速排序算法的例子中经常使用的是递归方式实现的。但递归算法的效率并不高,开销也较大。
此例子是使用了栈方式来代替递归方式实现了快速排序算法,可以在工作中参考一下。
算法中栈内存储的是待排序数组的数组标,对每次划分后的起始点和终止点进行压栈操作,然后从栈顶弹出一对起始点和终止点,再次进行快速排序的划分操作。
完整的算法(包括栈的实现的方法请到以下链接下载)
http://download.csdn.net/detail/wangzhiyu1980/4730049
main.cpp
#include <iostream>#include "mt_stack.h"using namespace std;void swap(int nA, int nB){ int nTmp = 0; nTmp = nA; nA = nB; nB = nTmp;}int split(void** pData, int nStart, int nEnd){ int nLow = nStart; int nHigh = nEnd; int nMid = nStart; int i = nLow; int j = nHigh; while (i < j) { while ((i < j) && (pData[nMid] > pData[i])) { i++; } while ((nMid < j) && (pData[nMid] < pData[j])) { j--; } if (i < j) { swap((int*)pData[i], (int*)pData[j]); } } return j;}void quickSort(void** pData, int nStart, int nEnd){ int nStackSize = nEnd - nStart; int nMid = 0; int nLow, nHigh; int* pTmp; if (nStart >= nEnd) return; MT_Stack *pStack = new MT_Stack(nStackSize); cout << "push:" << "(" << nStart << ", "<< nEnd << ")"<< endl; pStack->Push(nStart); pStack->Push(nEnd); while(!pStack->IsEmpty()) { pTmp = (int*)pStack->Pop(); nHigh = *pTmp; delete(pTmp); pTmp = (int*)pStack->Pop(); nLow = *pTmp; delete(pTmp); cout << "pop:"<< "(" << nLow << ", "<< nHigh << ")"<< endl; if (nLow < nHigh) { nMid = split(pData, nLow, nHigh); if (nMid > nLow) { cout << "push:" << "(" << nLow << ", "<< nMid << ")"<< endl; pStack->Push(nLow); pStack->Push(nMid); } if (nMid < nHigh) { cout << "push:" << "(" << nMid+1 << ", "<< nHigh << ")"<< endl; pStack->Push(nMid+1); pStack->Push(nHigh); } } }}int main(){ int arr[10] = {28, 203, 34, 19, 95, 82, 91, 643, 8293, 8487}; for (int i = 0; i < 10; i++) cout << arr[i] << " "; cout << endl; quickSort((void**)arr, 0, 9); for (int i = 0; i < 10; i++) cout << arr[i] << " "; cout << endl; return 0;}
测试结果
28 203 34 19 95 82 91 643 8293 8487
Create MT_Stack
push:(0, 9)
pop:(0, 9)
push:(1, 9)
pop:(1, 9)
push:(2, 9)
pop:(2, 9)
push:(3, 9)
pop:(3, 9)
push:(4, 9)
pop:(4, 9)
push:(5, 9)
pop:(5, 9)
push:(6, 9)
pop:(6, 9)
push:(7, 9)
pop:(7, 9)
push:(8, 9)
pop:(8, 9)
push:(9, 9)
pop:(9, 9)
19 28 34 82 91 95 203 643 8293 8487
- 快速排序算法 -- 非递归方式
- 非递归快速排序算法
- 快速排序非递归算法
- 快速排序非递归算法
- 快速排序(非递归算法)
- 快速排序 非递归算法
- 非递归快速排序算法
- 快速排序算法:非递归
- 快速排序递归和非递归算法
- [置顶]快速排序的递归方式和非递归方式
- 快速排序的非递归算法
- 非递归的快速排序算法
- 快速排序算法的非递归实现
- 快速排序的非递归算法
- 非递归的快速排序算法
- 非递归实现快速排序算法
- 快速排序的非递归算法实现
- 快速排序的递归算法和非递归算法
- POJ 3468 A Simple Problem with Integers 【线段数之插线问线】
- 【转载】Ubuntu下mex的运行
- c/c++资源(源码、开发工具、开发库)
- 【转载】Windows下用g++ MATLAB里面用mex
- C#给窗体添加皮肤-skinEngine的应用
- 快速排序算法 -- 非递归方式
- 字符编码笔记
- "WinMain”: 无法重载函数
- Intent 和 IntentFilter
- 某年某月有几天
- C++面向对象程序设计(谭浩强)阅读笔记2——类和对象
- java 键盘输入多种方法
- vs.net 2005没有找到MSVCR80D.dll的解决方案
- 新csdn的论坛看起来不错。