快速排序算法 -- 非递归方式

时间:2021-02-02 04:13:39

快速排序算法的例子中经常使用的是递归方式实现的。但递归算法的效率并不高,开销也较大。

此例子是使用了栈方式来代替递归方式实现了快速排序算法,可以在工作中参考一下。

算法中栈内存储的是待排序数组的数组标,对每次划分后的起始点和终止点进行压栈操作,然后从栈顶弹出一对起始点和终止点,再次进行快速排序的划分操作。


完整的算法(包括栈的实现的方法请到以下链接下载)

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