int Partition(int r[], int first, int end)
{
int i=first;
int j=end; //初始化第一个元素为key
while (i<j)
{
while (i<j && r[i]<= r[j])
j--; //右侧扫描
//走到这意味着i>=j||& r[i] > r[j],所以如果i<j,就进行交换
if (i<j) {
//将较小记录交换到前面
int temp = r[i];
r[i] = r[j];
r[j] = temp;
i++;
}
//交换之后,从左侧开始扫描
while (i<j && r[i]<= r[j])
i++;
if (i<j) {
//将较大记录交换到后面
int temp = r[i];
r[i] = r[j];
r[j] = temp;
j--;
}
}
for (int t = 0;t<7;t++)
{
cout<<r[t]<<" ";
}
cout<<endl;
return i; //i为轴值记录的最终位置
}
void QuickSort(int r[], int first, int end)
{
if (first<end) { //递归结束
int index=Partition(r, first, end); //一次划分
QuickSort(r, first, index-1); //递归地对左侧子序列进行快速排序
QuickSort(r, index+1, end); //递归地对右侧子序列进行快速排序
}
}
排序算法:快速排序
最新推荐文章于 2018-10-15 17:02:08 发布