快速排序是对冒泡排序的一种改进。它的基本思想是:通过一次排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一不部分的所有数据都要小,然后再按次方法对这两部分数据分别进行快速排序,整个排序过程可以递归或者非递归进行,以此达到整个数据变成有序序列。
下面是快速排序的递归实现:
#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#include using namespace std; template int partition(T a[],int low,int high) { T v=a[low]; while(low =v) high--; a[low]=a[high]; while(low void QuickSort(T a[],int p,int q) { stack st; int j; do{ while(p 本文地址:http://www.nowamagic.net/librarys/veda/detail/1194,欢迎访问原出处。


