快速排序的递归实现
2011-03-30
快速排序是对冒泡排序的一种改进。它的基本思想是:通过一次排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一不部分的所有数据都要小,然后再按次方法对这两部分数据分别进行快速排序,整个排序过程可以递归或者非递归进行,以此达到整个数据变成有序序列。
下面是快速排序的递归实现:
#include "stdafx.h"
#define LIST_INIT_SIZE 100 //顺序表初始大小
#define LISTINCREMENT 10 //顺序表增量
typedef int ElemType; //顺序表元素类型
typedef struct //顺序表结构
{
ElemType *elem;
int length;
int listsize;
}SqList;
//初始化顺序表
int InitList_Sq(SqList &L)
{
L.elem = (ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L.elem) return -1;
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return 0;
}
//创建顺序表
int CreatList_Sq(SqList &L)
{
InitList_Sq(L);
int i = 1;
while(scanf("%d",&L.elem[i]) != EOF)
{
i++;
}
L.length = i - 1;
return 0;
}
//一趟快速排序
int Partition(SqList &L,int low,int high)
{
L.elem[0] = L.elem[low];
int pivotkey;
pivotkey = L.elem[low];
int temp;
while(low < high)
{
while(low < high && L.elem[high] >= pivotkey) --high;;
L.elem[low] = L.elem[high];
while(low < high && L.elem[low] <= pivotkey) ++low;
L.elem[high] = L.elem[low];
}
L.elem[low] = L.elem[0];
return low;
}
//递归实现快速排序
void QuickSort(SqList &L,int low,int high)
{
if(low < high)
{
int pivotloc = Partition(L,low,high);
QuickSort(L,low,pivotloc - 1);
QuickSort(L,pivotloc + 1,high);
}
}
int _tmain(int argc, _TCHAR *argv[])
{
SqList L;
CreatList_Sq(L);
QuickSort(L,1,L.length);
for(int i = 1; i <= L.length; i++)
{
printf("%d ",L.elem[i]);
if(LIST_INIT_SIZE == i) printf("\n");
}
char ch = getchar();
return 0;
}
快速排序的非递归算法:
#include <iostream>
#include <stack>
using namespace std;
template <class T>
int partition(T a[],int low,int high)
{
T v=a[low];
while(low<high)
{
while(low<high && a[high]>=v) high--;
a[low]=a[high];
while(low<high && a[low]<=v) low++;
a[high]=a[low];
}
a[low]=v;
return low;
}
template <class T>
void QuickSort(T a[],int p,int q)
{
stack<int> st;
int j;
do{
while(p<q)
{
j=partition(a,p,q);
if( (j-p)<(q-j) )
{
st.push(j+1);
st.push(q);
q=j-1;
}
else
{
st.push(p);
st.push(j-1);
p=j+1;
}
}
if(st.empty()) return;
q=st.top();st.pop();
p=st.top();st.pop();
//cout<<endl<<"p:"<<p<<" ";
//cout<<"q:"<<q<<endl;
}while(1);
}
void main()
{
//int a[7]={7,6,5,4,3,2,1};
//int a[7]={1,2,3,4,5,6,7};
int a[7]={3,5,2,3,66,225,1};
for(int i=0;i<7;i++)
cout<<a[i]<<" ";
QuickSort(a,0,6);
cout<<endl;
for(int i=0;i<7;i++)
cout<<a[i]<<" ";
}
