#include <iostream>
using namespace std;
//快速排序思想简略:找到一个支点,使序列中支点左边的元素均小于支点元素,右边的元素均大于支点元素
//并把左边的元素看成一个新的序列,右边的元素同样也看成一个新序列,再对这两个新序列执行同样的操作(找支点)
//如此递归。。。直至只有一个元素为止
//分割函数
//交换顺序表val[low...high]中的记录,支点记录到位,返回其位置
int sort_partition(int val[],int low, int high)
{
int temp = val[low]; //用第一个元素作为支点元素
int pos = low; //
while (low < high)
{
//将记录比支点小的移动到低端 注:支点元素不移动
while (low < high && val[high] >= temp)
--high;
val[low] = val[high];
//将记录比支点大的移动到高端 注:支点元素不移动
while(low < high && val[low] <= temp)
++low;
val[high] = val[low];
}
val[low] = temp; //low == high
pos = low; //支点位置
return pos;
}//sort_partition
void quick_sort(int val[],int low, int high)
{
if (low < high)
{
int pos = sort_partition(val,low,high);
quick_sort(val,low,pos-1); //对子表递归排序
quick_sort(val,pos+1,high);
}
}//quick_sort
int main()
{
int val[] = {49,38,65,97,76,13,27,49};
int len = sizeof(val) / sizeof(int);
cout << "before quick_sort: " << endl;
for (int i = 0; i < len; i++)
{
cout << val[i] << endl;
}
cout << "quick_sort start..." << endl;
quick_sort(val,0,len-1);
cout << "quick_sort end..." << endl;
cout << "after the quick_sort ... " << endl;
for (int i = 0; i < len; i++)
cout << val[i] << endl;
return 0;
}