手敲二元堆積,堆排序,優先隊列

來源:互聯網
上載者:User

 早上倉促敲出來的,演算法大多數是YY出來的,不是很地道。晚上回來參考點資料,來個地道的。

這個排序叫冒泡更形象。

#include <stdio.h><br />#include <string.h><br />const int MaxN = 10001;</p><p>class Heap<br />{<br />public:<br />Heap():cnt(0){}<br />int Top(){<br />return a[1];<br />}<br />int min(int _a, int _b){<br />return a[_a] < a[_b] ? _a : _b;<br />}<br />int max(int _a , int _b){<br />return a[_a] > a[_b] ? _a : _b;<br />}<br />void swap(int _a , int _b){<br />a[_a] ^= a[_b] ^= a[_a] ^= a[_b];<br />}<br />void Pop(){<br />a[1] = a[cnt --];<br />int now = 1;<br />while ((now << 1) < cnt){<br />int tmp = min(now << 1 , 1 + (now << 1));<br />swap(now , tmp);<br />now = tmp;<br />}<br />if ((now << 1) == cnt && a[cnt] < a[now]){<br />swap(now , cnt);<br />}<br />}<br />void Push(int _a){<br />a[++ cnt] = _a;<br />int now = cnt;<br />while (now > 3){<br />int p1 = now >> 1 , p2 = p1 & 1 ? p1 + 1 : p1 - 1;<br />int tmp = max(p1 , p2);<br />if (a[now] >= a[tmp]) return;<br />swap(now , tmp);<br />now = tmp;<br />}<br />if (now > 1 && a[now] > a[1]){<br />swap(now , 1);<br />}<br />}<br />bool empty(){<br />return cnt == 0;<br />}<br />private:<br />int a[MaxN] , cnt;<br />};</p><p>void __test()<br />{<br />int i , j , n , a;<br />Heap H;<br />scanf("%d" , &n);<br />for (i = 0;i < n;i ++){<br />scanf("%d" , &a);<br />H.Push(a);<br />}<br />while (!H.empty()){<br />a = H.Top();H.Pop();<br />printf("%d " , a);<br />}<br />puts("");<br />}<br />int main()<br />{<br />__test();<br />}<br />/*<br />11<br />4 2 44 5 77 2 8 9 6 5 31<br />*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.