快速排序的核心思想:分治
1.先选取一个数作为基准数,一般选择分区的最左侧元素
2.分区过程,比基准数大的数放在右边,比基准数小的数放在左边。
3.对左右区间重复第二步,直到各区间只有一个数。
具体实现
low指向数组第一个元素(将其选为基准元素),high指向数组最后一个元素
第一步:high从右向左移动,若high指向的元素比l基准元素小(),交换两个元素,low右移一位
第二步:low从左向右移动,若low指向的元素比基准元素大,交换两个元素,high左移一位
两步交替执行直到low=high时,跳出循环。比基准元素小的数都到了基准元素左侧,大的数都到了右侧。也就是代码中的Partition函数,返回的结果是基准元素的下标。
#include "iostream"
using namespace std;
int Partition(int a[8],int low, int high,int temp);//temp是基准元素的下标,令temp=low,选择分区最左侧元素作为基准元素
void QuickSort(int a[8], int low, int high);
int main()
{
int a[8] = { 61, 33, 48, 82, 72, 11, 25, 48 };
int temp = 0;//存储基准元素所在位置
QuickSort(a, 0, 7);
for (int i = 0; i < 8; i++)
cout << a[i]<<" ";
system("pause");
return 0;
}
//大的数在基准元素右侧,小的数在基准元素左侧,从小到大排列
int Partition(int a[8],int low, int high,int temp)
{
while (low < high)
{
while (low<high)
{
if (a[temp] > a[high])//交换位置
{
int demo;
demo = a[temp];
a[temp] = a[high];
a[high] = demo;
temp = high;//temp是基准元素下标
break;
}
high--;//high从右向左搜寻
}
low = low + 1;
while (low < high)
{
if (a[low] > a[temp])
{
int demo;
demo = a[temp];
a[temp] = a[low];
a[low] = demo;
temp = low;
break;
}
low++;
}
high = high - 1;
}
for (int i = 0; i < 8; i++)
cout << a[i] << " ";
cout << endl;
return temp;
}
void QuickSort(int a[8], int low, int high)
{
if (low < high)
{
int temp = Partition(a, low, high, low);//默认将每个划分的最左侧元素当作基准元素
QuickSort(a, low, temp - 1);
QuickSort(a, temp + 1, high);
}
}