您的位置:首页 > 编程语言 > C语言/C++

堆排序算法实现(C++)

2012-04-17 15:47 211 查看
/*
* main.cpp
*
*  Created on: 2012-3-16
*      Author: csc
*/
#include <iostream>

using namespace std;

int a[] = {49,38,65,97,76,13,27,50};

void FixTree(int a[], int i)
{
cout<<"i: "<<i<<endl;
int j = (i-1)/2;
int temp =a[i];
while(j >= 0)
{
if(a[j] > a[i])
break;
temp = a[i];
a[i] = a[j];
a[j] = temp;
i = j;
if(j == 0)
break;
j = (j-1)/2;
}
}

void delete_elem_tree(int a[],int i, int n)
{
int temp = a[0];
i = 0;
int j = 2*i +1;
while(j<n)
{
if(j+1<n &&a[j+1]>a[j])
j++;
if(a[j]<temp)
break;
a[i] = a[j];
i = j;
j = 2*j+1;
}
a[i] = temp;
}

void insertTree(int a[], int n, int value)
{
a
= value;
FixTree(a, n);
}

int main(void) {

for(int i=1; i<8; i++)
{
insertTree(a, i, a[i]);
}

for(int i =0; i<8; i++)
cout<<a[i]<<" ";
cout<<endl;
a[0] = a[7];
delete_elem_tree(a,0, 7);
for(int i = 0; i<7; i++)
cout<<a[i]<<" ";
cout<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: