#include <stdio.h>
void QuickSort(int *pArry,int leftBound,int rightBound);
int main()
{
int array_data[]={1,3,5,7,9,2,4,6,8,10};
int * pArry=array_data;
int leftBound=0;
int rightBound=sizeof(array_data)/sizeof(int)-1;
QuickSort(pArry,leftBound,rightBound);
for (int i=0;i<=rightBound;i++)
{
printf("%d,",pArry[i]);
}
printf("\n");
return 0;
}
void swap(int &a,int &b)
{
int tmp=a;
a=b;
b=tmp;
}
void QuickSort(int *pArry,int leftBound,int rightBound)
{
if (leftBound>=rightBound)
{
return;
}
int keyPos = leftBound;
bool changed=false;
do{//我实现的未必是最高效的快排,但符合快排的思想
changed=false;
for (int i=leftBound;i<=rightBound;i++)
{
if (i<keyPos && pArry[i] > pArry[keyPos])
{
swap(pArry[i], pArry[keyPos]);
keyPos=i;
changed=true;
}
else if (i>keyPos && pArry[i] < pArry[keyPos])
{
swap(pArry[i], pArry[keyPos]);
keyPos=i;
changed=true;
}
}
}while(changed);
QuickSort(pArry,leftBound,keyPos-1);
QuickSort(pArry,keyPos+1,rightBound);
}
/*
1,2,3,4,5,6,7,8,9,10,
请按任意键继续. . .
*/
/*
它的基本思想是:
首先从待排序序列中选一个关键字作为枢轴,
使枢轴左边的所有数据都小于这个枢轴,
枢轴右边的数据都大于这个枢轴,
再用递归的方法对这两个子序列进行快速排序,
最终使得整个序列有序
*/
//网上的快排代码
void QuickSort_0(int *pArry,int leftBound,int rightBound)
{
if (leftBound>=rightBound)
{
return;
}
int key = pArry[leftBound];
int low = leftBound;
int high = rightBound;
while(low < high){
while(low < high && pArry[high] > key){
high--;
}
pArry[low] = pArry[high];
while(low < high && pArry[low] < key){
low++;
}
pArry[high] = pArry[low];
}
pArry[low] = key;
QuickSort_0(pArry,leftBound,low-1);
QuickSort_0(pArry,low+1,rightBound);
}
/*
1,2,3,4,5,6,7,8,9,10,
请按任意键继续. . .
*/