#include<iostream>
#include<string>
#include "string"
#include<vector>
#include<stack>
#include<stdlib.h>
#include"algorithm"
using namespace std;
int partition(vector<int> &array, int low, int high)
{
//先以最左边的数作为基准
int base = array[low];
while(low < high)
{
//从序列右端开始,向左遍历,直到找到小于base的值
while(low < high&&array[high] >= base)
{
high--;
}
//找到比base小的数,将这个元素放在最左边的位置
array[low] = array[high];
//从序列的左端开始,向右遍历,直到找到大于base的值
while(low < high && array[low] <= base)
{
low++;
}
//找到比base大的数,将这个元素放在最右边的位置
array[high] = array[low];
}
//最后当low = high时,将base放到low的位置上,此时base左边的数比base小,右边的数比base大
array[low] = base;
return low;
}
void QuickSort(vector<int> &array, int low, int high)
{
//左下标一定要小于右下标
if(low < high)
{
//对数组进行分割
int base = partition(array, low, high);
//对基准base标号左侧的数组进行递归切割,将这些数值排序
QuickSort(array, low, base - 1);
//对基准base标号右侧的数值进行排序
QuickSort(array, base + 1, high) ;
}
}
int main()
{
int arr[] = { 6, 4, 8, 9, 2, 3, 1 };
vector<int> test(arr, arr+sizeof(arr)/sizeof(arr[0]));
cout << "before:"<< endl;
for(int i = 0; i < test.size(); i++)
{
cout << test[i] << " ";
}
cout << endl;
cout << "after:" <<endl;
QuickSort(test, 0, test.size()-1);
for(int i = 0; i < test.size(); i++)
{
cout << test[i] << " ";
}
cout << endl;
return 0;
}
数据结构与算法_快速排序
最新推荐文章于 2022-05-23 11:21:34 发布