zoukankan      html  css  js  c++  java
  • 堆排序

    #include <bits/stdc++.h>
    using namespace std;
    const int N = 2e5 + 20;
    const int mod = 1e9 + 7;
    #define ll long long
    #define P pair<int,int>
    #define mk make_pair
    int heap[N];
    int n;
    void downAdjust(int low,int high)
    {
        int i = low,j = i * 2;
        while(j <= high)
        {
            if(j + 1 <= high && heap[j] < heap[j+1])
            {
                j++;
            }
            if(heap[j] > heap[i])
            {
                swap(heap[j],heap[i]);
                i = j;
                j = i * 2;
            }
            else
            {
                break;
            }
        }
    
    }
    void createHeap()
    {
        for(int i=n/2;i>=1;i--)
        {
            downAdjust(i,n);
        }
    }
    int main() {
        cin >> n;
        for (int i = 1; i <= n; i++) {
            cin >> heap[i];
        }
        createHeap();
        for (int i = n; i > 1; i--) {
            swap(heap[i], heap[1]);
            downAdjust(1, i - 1);
        }
        for(int i=1;i<=n;i++)
        {
            cout << heap[i] << " ";
        }
    
    
    
        return 0;
    }
    /*
    6
    6 1 2 7 2 8
    14
     */
    
  • 相关阅读:
    微信红包高并发交易
    MQ夺命11问
    美团雪花LEAF算法
    Mysql一遍过
    分布式
    如何注册和发现服务
    服务发布和引用
    微服务的构成
    什么是微服务
    Java的动态代理
  • 原文地址:https://www.cnblogs.com/hh13579/p/14648490.html
Copyright © 2011-2022 走看看