您的位置:首页 > 理论基础 > 数据结构算法

C++堆(数据结构堆也就是树状结构)排序

2018-03-11 15:54 197 查看
#include<iostream>
using namespace std;

int arr[10] = { 2,8,3,9,1,4,6,7,0,5 };
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

void show(int *arr,int n)
{
for (size_t i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;

}

void heapsort(int *arr, int n)
{
for (size_t i = n; i >0; i--)
{
for (size_t j = i-1; j > 0; j--)
{
int childen = j;
int father = j / 2;

if (j<i-1&&arr[j]<arr[j+1])
{
childen++;
}

if (arr[childen]>arr[father])
{
swap(arr[childen], arr[father]);
}

}

swap(arr[0], arr[i - 1]);

}

}
int main(int argc, char *argv[])
{
heapsort(arr, 10);
show(arr,10);

system("pause");

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: