#include <iostream>
using namespace std;
//堆排
//维护堆
void maxheapify(int *a, int cur, int low, int high)
{
int large = 2 * low + 1;
while(large < high)
{
if(large < high && a[large] < a[large + 1])
large++;
if(cur >= a[large]){
break;
}else{
a[low] = a[large];
low = large;
large = 2 * low + 1;
}
}
a[low] = cur;
}
//建立堆
void buildheap(int *a, int n)
{
int i,j;
for(i = (n>>1) - 1; i >=0; i--){
int cur = a[i];
maxheapify(a,cur,i,n-1);
}
}
//堆排序
void heapsort(int *a, int n)
{
buildheap(a,n);
int i = n-1;
for(i = n-1; i >= 0; i--){
int cur = a[i];
a[i] = a[0];
maxheapify(a,cur,0,i - 1);
}
}
//交换
inline void myswap(int &x,int &y)
{
int tmp = x;
x= y;
y = tmp;
}
//冒泡排序
void bubblesort(int *a, int n)
{
int i,j;
for(i=0;i<n;i++)
{
for(j=n-1;j>i;j--){
if(a[j-1]>a[j])
{
myswap(a[j-1],a[j]);
}
}
}
}
//插入排序
void insertsort(int *a,int n)
{
int i,j;
for(i = 1; i<n;i++){
for(j = i;j >=1;j--){
if(a[j]<a[j-1])
myswap(a[j],a[j-1]);
else break;
}
}
}
//选择排序
void selectsort(int *a,int n)
{
int i,j;
for(i=n-1;i>=0;i--){
int maxi = i;
for(j=i-1;j>=0;j--){
if(a[j] > a[maxi])
maxi = j;
}
myswap(a[i],a[maxi]);
}
}
//shell插入
void shellinsert(int *a,int n,int inc)
{
int i,j;
for(i=inc;i<n;i+=1)
{
for(j=i;j>=inc;j=j-inc){
if(a[j] < a[j-inc])
myswap(a[j],a[j-inc]);
else break;
}
}
}
//shell排序
void shellsort(int *a,int n)
{
int i,inc;
inc= n;
do{
inc = inc/3+1;
shellinsert(a,n,inc);
}while(inc > 1);
}
//合并
void merge(int *a,int p,int q)
{
int l = p;
int r = (p+q)/2 + 1;
int mid = r;
int *tmp = new int[q-p+1];
int i = 0;
while(l < mid || r <=q){
if(l >= mid){
tmp[i++] = a[r++];
}else
if(r > q){
tmp[i++] = a[l++];
}else{
if(a[l] < a[r]){
tmp[i++] = a[l++];
}else{
tmp[i++] = a[r++];
}
}
}
int k = p;
for(int j = 0;j<i;j++){
a[k++] = tmp[j];
}
delete[] tmp;
}
//合并排序
void mergesort(int *a,int p,int q)
{
if(p>=q)
return ;
int mid = (p+q)/2;
mergesort(a,p,mid);
mergesort(a,mid+1,q);
merge(a,p,q);
}
//快速排序
void quicksort(int *a,int p, int q)
{
if(p>=q)
return;
int pivot = p;
int i = p,j = q;
while(i<j){
while(i<j && a[j] >= a[pivot])
j--;
while(i<j && a[i] <= a[pivot])
i++;
if(i<j)
myswap(a[i],a[j]);
}
myswap(a[i],a[pivot]);
quicksort(a,p,i-1);
quicksort(a,i+1,q);
}
//测试
int main()
{
int a[] = {2,5,3,5,7,4,8,1};
int n = 8;
// heapsort(a,n);
// bubblesort(a,n);
// insertsort(a,n);
// selectsort(a,n);
// shellsort(a,n);
// mergesort(a,0,n-1);
quicksort(a,0,n-1);
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}