#include <stdio.h>
//Printf the element of the array
void PrintfArray(int *Array, int front, int rear)
{
for(int i = front; i <= rear; i++)
{
printf("%d\t", *(Array+i));
}
printf("\n");
}
//Data swap function
void Swap(int &p, int &q)
{
int temp = p;
p = q;
q = temp;
}
//算法导论提供的分割算法
int Partition(int ArrayInput[], int nLow, int nHigh)
{
int pivotkey = ArrayInput[nHigh]; //取最后一个元素作为枢轴
int j = nLow - 1;
int i = nLow;
for(; i < nHigh; i++)
{
if(ArrayInput[i] <= pivotkey)
{
j++; //j指向的位置是当前大于枢轴的前一元素
if(i != j)
{
Swap(ArrayInput[i], ArrayInput[j]);
}
}
}
Swap(ArrayInput[j+1], ArrayInput[nHigh]);
return (j + 1);
}
//数据结构教材的分割算法
int Partition(int ArrayInput[], int nLow, int nHigh)
{
int pivotkey = ArrayInput[nLow]; //取第一个元素作为枢轴
int i = nLow;
int j = nHigh;
while(i < j)
{
while((i < j) && (ArrayInput[j] >= pivotkey))
{
--j;
}
Swap(ArrayInput[j], ArrayInput[i]);
while((i < j) && (ArrayInput[i] <= pivotkey))
{
++i;
}
Swap(ArrayInput[i], ArrayInput[j]);
}
return i;
}
//Quick sort
void Quick_sort(int ArrayInput[], int nLow, int nHigh)
{
if(nLow < nHigh)
{
int nIndex = Partition(ArrayInput, nLow, nHigh);
Quick_sort(ArrayInput, nLow, nIndex - 1);
Quick_sort(ArrayInput, nIndex + 1, nHigh);
}
}
int main()
{
int A[50] = {5, 3, 4, 2, 6, 8, 9, 0, 1, 7,
21,23,25,27,30,29,22,24,26,28,
11,13,15,17,20,19,12,14,16,18,
58,56,54,52,59,60,57,55,53,51,
71,73,75,77,80,79,72,74,76,78};
int Arraylen = sizeof(A)/sizeof(int);
PrintfArray(A, 0, Arraylen - 1);
Quick_sort(A, 0, Arraylen - 1);
printf("after Quick_sort:\n");
PrintfArray(A, 0, Arraylen - 1);
return 0;
}