堆排序(自己版本)

来源:互联网 发布:matlab利用空矩阵赋值 编辑:程序博客网 时间:2024/06/10 16:03
#include<iostream>
#include<vector>
using namespace std;
void heap_adjust(vector<int>& v, int node_bh, int last_node_bh)
{
if (node_bh <= last_node_bh)
{
int father = node_bh;
int node_need_adjust;
bool adjust = false;
int left_child = node_bh * 2 + 1;
int right_child = node_bh * 2 + 2;
if (left_child <= last_node_bh)
{
if (v[father] < v[left_child])
{
node_need_adjust = left_child;
adjust = true;
}
}
if (right_child <= last_node_bh)
{
if (v[left_child] < v[right_child])
{
node_need_adjust = right_child;
adjust = true;
}
}
if (adjust == true)
{
int temp = v[father];
v[father] = v[node_need_adjust];
v[node_need_adjust] = temp;
heap_adjust(v, node_need_adjust, last_node_bh);
}
}
}
void heap_sort(vector<int>& v,int len)
{
for (int i = len-1; i >=0; i--)//从无到有建立大顶堆,实际是个不断进行调整的过程,注意大顶堆并不是小层的数据都比大层的数据大
{
heap_adjust(v,i,len-1);
}
for (int j = len - 1; j > 0; j--)//逐渐产生整个有序数组
{
int temp;
temp = v[0];
v[0] = v[j];
v[j] = temp;
heap_adjust(v,0,j-1);
}
}
int main()
{
int n;
vector<int> v;
cout << "input n" << endl;
cin >> n;
cout << "input nums" << endl;
for (int i = 0; i < n; i++)
{
int temp;
cin >> temp;
v.push_back(temp);
}
heap_sort(v, v.size());
return 0;
}
原创粉丝点击