基本思想:
随机找出一个数,可以随机取,也可以取固定位置,一般是取第一个或最后一个称为基准,然后就是比基准小的在左边,比基准大的放到右边,如何放做,就是和基准进行交换,这样交换完左边都是比基准小的,右边都是比较基准大的,这样就将一个数组分成了两个子数组,然后再按照同样的方法把子数组再分成更小的子数组,直到不能分解为止。
程序设计:
void sAlgorithm::quickSort(std::vector<int>& outData, int i, int j)
{
if (i > j)
return;
int start = outData[i]; //基准为第一个数
int low = i;
int high = j;
while (low < high)
{
while (low < high && start < outData[high])
high--;
outData[low] = outData[high];
while (low < high && start >= outData[low])
low++;
outData[high] = outData[low];
}
outData[low] = start;
//再次循环排序
quictSort(outData, i, low - 1);
quictSort(outData, low + 1, j);
return ;
}
程序测试:
int main()
{
sAlgorithm ss;
std::vector<int> outNum;
ss.dataCreat(10, outNum);
std::vector<int> oriNum(outNum);
ss.quickSort(outNum, 0, outNum.size() - 1);
cout << "原序列:";
for (int i = 0; i < oriNum.size(); i++)
{
cout << oriNum[i] << " ";
}
cout << endl;
cout << "排序后:";
for (int i = 0; i < outNum.size(); i++)
{
cout << outNum[i] << " ";
}
cout << endl;
return 0;
}
测试结果:
原序列:55 6 97 91 29 92 61 0 76 5
排序后:0 5 6 29 55 61 76 91 92 97
网友评论