堆排序算法實現

// HeapSort.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include<iostream>
using namespace std;


void Swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void HeapAdjust(int a[],int s, int e)
{
a[0] = a[s];         //a[0]作爲一箇中間值
for (int j = 2 * s; j <= e; j *= 2) //節點從1開始標註,
{
if (j < e && (a[j] < a[j + 1]))
j++;
if (a[0] >= a[j])
break;
a[s] = a[j];
s = j;
}
a[s] = a[0];
}


void HeapSort(int a[], int length)
{
for (int i = length / 2; i > 0; i--)//從完全二叉樹的最後一個有孩子的節點開始,自下而上遍歷
{
HeapAdjust(a,i,length);
}
for (int i = length; i > 1; --i)
{
Swap(a[1],a[i]);    //將堆頂元素和堆最後一個元素交換
HeapAdjust(a,1,i-1); //重新將剩餘的元素構建成大頂堆
}
}


int main()
{
int a[] = {0,3,5,69,33,56,2,55,19};
HeapSort(a, 8);
for (int i = 1; i <= 8; i++)
cout << a[i] << "\t";
getchar();
    return 0;
}

發佈了40 篇原創文章 · 獲贊 13 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章