堆排序實現

來源:互聯網
上載者:User
// 演算法.cpp : 定義控制台應用程式的進入點。//對於堆排序來說,邏輯上是樹的形式,實際儲存的形式還是數組。只是對下標進行一定的計算獲得邏輯上樹的形式。//此堆的結構為0號位為根結點,沒有左子樹,右邊接著以1號位置為根結點的子樹。#include "stdafx.h"#include <iostream>using namespace std;const int HEAP_SIZE = 13; //堆大小int  parent(int);int  left(int);int  right(int);void Max_Heapify(int [], int, int);void Build_Max_Heap(int []);void print(int []);void HeapSort(int [], int);int _tmain(int argc, _TCHAR* argv[]){int A[HEAP_SIZE] = {19, 1, 10, 14, 16, 4, 7, 9, 3, 2, 8, 5, 11};    HeapSort(A, HEAP_SIZE);    system("pause");    return 0;}//獲得左子結點int left(int i){    return 2 * i;} //獲得右子結點int right(int i){    return (2 * i + 1);} //最大根結點調整void Max_Heapify(int A[], int i, int heap_size){    int l = left(i);    int r = right(i);    int largest;    int temp;//找出三個結點中最大的一個    if(l < heap_size && A[l] > A[i])    {        largest = l;    }    else    {        largest = i;    }    if(r < heap_size && A[r] > A[largest])    {        largest = r;    }//將最大的結點設定為根結點    if(largest != i)    {        temp = A[i];        A[i] = A[largest];        A[largest] = temp;//遞迴實現子樹最大根結點        Max_Heapify(A, largest, heap_size);    }}//建立最大堆void Build_Max_Heap(int A[]){    for(int i = (HEAP_SIZE-1)/2; i >= 0; i--)    {//子樹最大堆調整        Max_Heapify(A, i, HEAP_SIZE);    }} //列印樹void print(int A[]){    for(int i = 0; i < HEAP_SIZE;i++)    {        printf("%d ", A[i]);    }    printf("\n");} //堆排序void HeapSort(int A[], int heap_size){    Build_Max_Heap(A);    int temp;    for(int i = heap_size - 1; i > 0; i--)    {//將最大的放在堆尾        temp = A[0];        A[0] = A[i];        A[i] = temp;//最大根結點調整        Max_Heapify(A, 0, i);    }    print(A);} 

  Flash http://ds.fzu.edu.cn/fine/resources/FlashContent.asp?id=88

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.