前言
最近学习了快速排序,简单记录一下。
引例:三色旗问题
问题描述:
有一个只由0,1,2三种元素构成的整数数组,请使用交换、原地排序而不是使用计数进行排序。
解题思路:
定义两个下标left和right;
left的含义:使数组中<=left的部分都比1小,left的初始值为-1;
right的含义:使数组中>=right的部分都比1大,right的初始值为n;
从index = 0开始遍历;
根据index所指向的值分别进行不同的操作;
如果a[index] = 0,与left对应的值交换;
如果a[index] = 1,index++;
如果a[index] = 2,与right对应的值交换。
代码如下:
void holand(int a[], int n) {
int index = 0, left = -1, right = n;
while (index < right) {
if(a[index] == 0) {
swap(a[index++], a[++left]);
}
else if (a[index] == 1) {
index++;
}
else if (a[index] == 2) {
swap(a[index