C++-快速排序[STL][快速排序][并归排序][堆排序]

 1 #include <queue>
 2 #include <iostream>
 3 using namespace std;
 4 priority_queue<int>q;
 5 int main(){
 6     for(int a;cin>>a;q.push(-a))
 7         if(a==0){
 8             for(;!q.empty();q.pop())cout<<-q.top()<<" ";
 9             return 0;
10         }
11 } 
 1 #include <iostream>
 2 using namespace std;
 3 const int N=1e6+20;
 4 int a[N],n;
 5 void sort(int a[],int l,int r){
 6     if(l>r)return;
 7     int L=l,R=r,key=a[l];
 8     while(L<R){
 9         while(L<R&&a[R]>=key)R--;a[L]=a[R];
10         while(L<R&&a[L]<=key)L++;a[R]=a[L];
11     }
12     a[L]=key;
13     sort(a,l,L-1);
14     sort(a,L+1,r);
15 }
16 int main(){
17     for(int i;cin>>i;a[++n]=i)if(i==0)break;
18     sort(a,1,n);
19     for(int i=1;i<=n;i++)cout<<a[i]<<" ";
20     return 0;
21 }
 1 #include <iostream>
 2 using namespace std;
 3 const int N=1e6+20;
 4 int a[N],n,t[N];
 5 void merge(int a[],int L,int R){
 6     if(L>=R)return;
 7     int M=(L+R)>>1;
 8     merge(a,L,M);
 9     merge(a,M+1,R);
10     if(a[M]<=a[M+1])return;//优化 
11     int l=L,r=M+1,n=0;
12     while(l<=M&&r<=R)t[++n]=a[l]<=a[r]?a[l++]:a[r++];
13     while(l<=M)t[++n]=a[l++];
14     while(r<=R)t[++n]=a[r++];
15     for(int i=L,j=1;i<=R;a[i++]=t[j++]);
16 }
17 int main(){
18     for(int i;cin>>i;a[++n]=i)if(i==0)break;
19     merge(a,1,n);
20     for(int i=1;i<=n;i++)cout<<a[i]<<" ";
21     return 0;
22 }

 

 1 #include <iostream>
 2 using namespace std;
 3 const int N=1e7+10;
 4 struct heap{
 5     int a[N],n;    
 6     int top(){return a[1];}
 7     bool empty(){return n==0;}
 8     void push(int x){a[++n]=x,up(n);}
 9     void pop(){swap(a[1],a[n--]),down(1);}
10     void up(int x){
11         for(int f;x>1,f=x>>1;x=f){
12             if(a[f]>a[x])swap(a[f],a[x]);
13             else return;
14         }
15     }
16     void down(int x){
17         for(int ls,rs,p;(x<<1)<=n;x=p){
18             ls=x<<1,rs=x<<1|1;
19             p=rs<=n&&a[rs]<a[ls]?rs:ls;
20             if(a[p]<a[x])swap(a[p],a[x]);
21             else return;
22         }
23     }
24 };
25 heap q;
26 int main(){
27     for(int a;cin>>a;q.push(a))if(a==0)break;
28     while(!q.empty())cout<<q.top()<<" ",q.pop();cout<<endl;
29     return 0;
30 }

 

posted @ 2020-03-09 13:25  墨鳌  阅读(356)  评论(0编辑  收藏  举报