堆排序算法实现(C++)
来源:互联网 发布:大数据存储和处理 编辑:程序博客网 时间:2024/05/16 16:56
/* * 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[n] = 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;}