快速排序
递归法:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <bits/stdc++.h>
using namespace std;
int partition(int a[], int left, int right)
{
int i = left, j = right; //以 a[left]为基准数
while(i < j)
{
while( i < j && a[j] > a[left] ) //从右边开始遍历,如果比基准数a[left]大,则继续向左遍历
j--;
while( i < j && a[i] <= a[left])//从左边开始遍历,如果比基准数a[left]小或者相等,则继续向右遍历
i++;
swap(a[i], a[j]); //当左右遍历,不满足条件时,交换两边开始不满足条件的起始位置。
}
swap(a[i], a[left]); // 基准数 a[left] 交换到指定的位置
return i;
}
void QuickSort(int a[], int left, int right)
{
if(left < right)
{
int pivot = partition(a, left, right); // 进行一次排序,找到枢轴的位置
QuickSort(a, left, pivot-1); // 对枢轴左边的区间进行快排
QuickSort(a, pivot+1, right); // 对枢轴右边的区间进行快排
}
}
int main()
{
int a[9];
int n = 9;
for(int i=0; i<n; i++)
{
cin >> a[i];
}
QuickSort(a, 0, n-1); //进行快速排序
for(int i=0; i<n; i++)
{
cout<< a[i] <<' ';
}
cout << endl;
return 0;
}
非递归法:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int partition(vector<int>& num,int left, int right)
{
int i = left, j = right;
while(i < j)
{
while(i < j && num[j] > num[left])
j--;
while(i < j && num[i] <= num[left])
i++;
swap(num[i], num[j]);
}
swap(num[i], num[left]);
return i;
}
void QuickSort(vector<int>& num, int begin, int end)
{
stack<int>s; // 主要是借助栈存储每次partition划分时的左右边界值
int left = begin;
int right= end;
s.push(right);
s.push(left);
while(!s.empty())
{
left = s.top();
s.pop();
right = s.top();
s.pop();
if(left < right)
{
int pivot = partition(num, left, right);
if(pivot-1 > left)
{
s.push(pivot-1);
s.push(left);
}
if(pivot+1 < right)
{
s.push(right);
s.push(pivot+1);
}
}
}
}
int main()
{
int a[] = {1,567,4,3,6,5,3465,567};
vector<int>num(a, a+8);
for(int i=0; i<num.size(); i++)
cout<<num[i]<<' ';
cout<<endl;
QuickSort(num, 0, 7);
for(int i=0; i<num.size(); i++)
cout<<num[i]<<' ';
cout<<endl;
return 0;
}