快速排序的思想在程序中经常用到,虽然C++给出了快速排序的函数调用,但是很多程序可能需要自己写排序过程,快速排序就会被用到,以下是快速排序算法:

快速排序时间复杂度是O(nlog(n)),在数据有序的情况下最耗时

(程序输入如果使用scanf_s则编译器为vs2013)

#include

#include

#define  MAXSIZE  1<<9


typedef struct {

int key;

}RedType;


typedef  struct  {

RedType elemword[MAXSIZE];

int count;

}SqList;


void InitialSqList(SqList &);

void QuickSort(SqList &);

void QSort(SqList &, int, int);

int Partition(SqList &, int, int);

void PrintSqList(SqList);


void InitialSqList(SqList &L)

{

int i;

scanf("%d", &L.count);

for (i = 1; i <= L.count; i++)

scanf("%d", &L.elemword[i].key);

}


void PrintSqList(SqList L)

{

int i;

for (i = 1; i <= L.count; i++)

printf("%d", L.elemword[i].key);

printf("\n");

}


void QSort(SqList &L, int low, int high)

{

int pivotloc;

if (low

{

pivotloc = Partition(L, low, high);

QSort(L, low, pivotloc - 1);

QSort(L, pivotloc + 1, high);

}

}


void QuickSort(SqList &L)

{

QSort(L, 1, L.count);

}


int Partition(SqList &L, int low, int high)

{

int pivotkey;

pivotkey = L.elemword[low].key;

while (low

{

while (low= pivotkey)

--high;

L.elemword[low].key = L.elemword[high].key;

while (low

++low;

L.elemword[high].key = L.elemword[low].key;

}

L.elemword[low].key = pivotkey;

return low;

}


int main()

{

SqList L;

int i;

while (scanf("%d",&L.count)!=EOF)

{

L.count = L.count + 1;

for (i = 1; i <= L.count; i++)

scanf("%d", &L.elemword[i].key);

QuickSort(L);

PrintSqList(L);

}

return 0;

}