排序代码:
void quickSort(int a[], int left, int right)
{
if (left >= right) return;
int i = left;
int j = right;
//记录基准值
int base = a[left];
while (i < j)
{
//从右向左找小于基准值的数
while (i < j && a[j] >= base)
j--;
//从左向右找大于基准值的数
while (i < j && a[i] <= base)
i++;
//交换
if (i < j)
std::swap(a[i], a[j]);
}
//基准值和中间i位置交换
a[left] = a[i];
a[i] = base;
//此时i左侧全部小于基准值,右侧全部大于基准值,从i两边分别递归即可
quickSort(a, left, i - 1);
quickSort(a, i + 1, right);
}
测试:
int a[] = { 9,5,7,8,4,1,2,6,3,10 };
std::cout << "sort before:" << std::endl;
for (size_t i = 0; i < 9; i++)
std::cout << a[i] << " ";
quickSort(a, 0, 9);
std::cout << std::endl << "sort after:" << std::endl;
for (size_t i = 0; i < 9; i++)
std::cout << a[i] << " ";
输出结果: