C++ 快排

来源:互联网 发布:时间序列数据集 编辑:程序博客网 时间:2024/06/17 06:00
#include <iostream>


void swap(int *beg, int *end);
int * Partition(int *beg, int *end);
void QSort(int *beg, int *end);


int main()
{
int arr[7] = { 3, 9, 8, 2, 3, 5, 6 };
int *beg = std::begin(arr);
int *end = std::end(arr) - 1;//end(), 返回尾后迭代器


QSort(beg, end);
while (beg <= end)
{
std::cout << *beg++ << std::endl;
}
system("pause");
return 0;
}


int * Partition(int *beg, int *end)
{
int pivot = *beg;
while (beg < end)
{
while (beg < end && *end >= pivot)//从右向左寻找关键字小于pivot的值
{
--end;
}
swap(end, beg);
while (beg < end && *beg <= pivot)//从左向右寻找关键字大于等于pivot的值
{
++beg;
}
swap(beg, end);
}
return beg;
}


void swap(int *beg, int *end)
{
int tmp = *beg;
*beg = *end;
*end = tmp;
}


void QSort(int *beg, int *end)
{
if (beg < end)
{
int *pivotLoc = Partition(beg, end);
QSort(beg, pivotLoc - 1);
QSort(pivotLoc + 1, end);
}
}