【模板】快速排序

P1177 【模板】快速排序

【 堆排序 】

      时间复杂度:O(nlogn)      PS:OI界的log都是以2为底数

      空间复杂度:O(n)

      [ 代码 ]:

#include<bits/stdc++.h>

using namespace std;

long long n,x,heap_size;
int heap[100001];

void put(int d)
{
    int now,next;
    heap[++heap_size]=d;
    now=heap_size;
    while(now>1)
    {
        next=now>>1;
        if(heap[now]>=heap[next]) break; //小根堆
// if(heap[now]<=heap[next]) break; //大根堆
else swap(heap[now],heap[next]); now=next; } } int get() { int now,next,res; res=heap[1]; heap[1]=heap[heap_size--]; now=1; while(now*2<=heap_size) { next=now*2; if(next<heap_size&&heap[next+1]<heap[next]) next++; //小根堆
// if(next<heap_size&&heap[next+1]>heap[next]) next++; //大根堆
if(heap[now]>heap[next]) //小根堆
// if(heap[now]<heap[next]) //大根堆 swap(heap[now],heap[next]); now
=next; } return res; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&x); put(x); } for(int i=1;i<=n;i++) cout<<get()<<" "; return 0; }

【简练版本】

 使用C++标准模板库STL(需要头文件 algorithm)

#include<bits/stdc++.h>
#include<algorithm>

using namespace std;

long long n,x,heap_size;
int heap[100001];

void put(int d)
{
    
    heap[++heap_size]=d;
//  push_heap(heap+1,heap+heap_size+1);                //大根堆 
    push_heap(heap+1,heap+heap_size+1,greater<int>()); //小根堆 
}

int get()
{
//    pop_heap(heap+1,heap+heap_size+1);              //大根堆 
    pop_heap(heap+1,heap+heap_size+1,greater<int>()); //小根堆 
    return heap[heap_size--];
}
 【 快排 】

      时间复杂度:O(nlogn)      PS:OI界的log都是以2为底数

      空间复杂度:O(nlogn)

      [ 代码 ]:(从小到大)

#include<bits/stdc++.h>

using namespace std;

long long n;
int a[100001];

int main()
{
     scanf("%d",&n);
     for(int i=1;i<=n;i++)
         scanf("%d",&a[i]);
     
     sort(a+1,a+n+1);
     
     for(int i=1;i<=n;i++)
        cout<<a[i]<<" ";
     
     return 0;    
}
原文地址:https://www.cnblogs.com/xiaoyezi-wink/p/10776687.html