快速排序
来源:互联网 发布:阿里云 io hang 编辑:程序博客网 时间:2024/06/01 11:22
#include<iostream>using namespace std;template <class Type>void Swap(Type &a,Type &b){ Type tem=a; a=b; b=tem;}template <class Type>int Partition(Type a[],int p,int r){ int i=p,j=r+1; Type x=a[p]; while(true) { while(a[++i]<x && i<r); while(a[--j]>x); if(i>=j) break; Swap(a[i],a[j]); } a[p]=a[j]; a[j]=x; return j;}template <class Type>void QuickSort(Type a[],int p,int r){ if(p<r) { int q=Partition(a,p,r); QuickSort(a,p,q-1); QuickSort(a,q+1,r); }}int main(){ int n; cout<<"请输入数组的长度"<<endl; cin>>n; int a[n]; cout<<"请输入数组的各个元素"<<endl; for(int i=0;i<n;i++) { cin>>a[i]; } QuickSort(a,0,n-1); cout<<"排好序的数组各个元素是"<<endl; for(int i=0;i<n;i++) { cout<<a[i]<<" "; } cout<<endl;}