vector<int> selectSort(vector<int> &nums)
{
int len = nums.size();
cout << len;
for (int i = 0; i < len - 1; i++)
{
//假定nums[i]为最大,遍历i以后的数,找实际最大
int max = i;
for (int j = i + 1; j < len; j++)
{
if (nums[j] > nums[max])
{
max = j;
}
}
//最大值是本身nums[i],不必交换,最大值不是本身交换
if (max != i)
{
swap(nums[i], nums[max]);
}
}
return nums;
}
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
/* 以最大堆为例:升序
一维数组存储完全二叉树:
根据节点的下标i,可以得到其父节点的下标(i-1)/2
子节点1: 2i+1
子节点2: 2i+2
*/
// heapify成堆过程:找当前节点i与其两个子节点c1、c2的最大值,调整最大值在根节点位置
void heapify(vector<int> &tree, int n,int i)
{
if (i >= n)//递归出口
return;
int child1 = 2 * i + 1; //子节点1
int child2 = 2 * i + 2; //子节点2
//找当前节点与两个子节点中的最大值
int max = i;
if (child1 < n && tree[child1] > tree[max]) //判断是否为终叶节点,防止子节点出界
max = child1;
if (child2 < n && tree[child2] > tree[max])
max = child2;
//最大值不是i,则与当前节点i交换
if (max != i)
{
swap(tree[max], tree[i]);
heapify(tree, n, max);//继续成堆,递归调用
}
}
//构造堆
void build_heap(vector<int> &tree,int n)
{
//找最后一个节点的根节点
int last = n - 1;
int parent = (last - 1) / 2;
//自底向上成堆
for (int i = parent; i >= 0; i--)
{
heapify(tree, n, i);
}
}
//堆排序
//根节点为最大值,根节点与最后一个节点交换,然后成堆....重复以上过程
void heap_sort(vector<int> &tree, int n)
{
build_heap(tree, n); //构造堆
for (int i = n - 1; i >= 0; i--)//从最后一个节点开始
{
swap(tree[0], tree[i]); //与最后一个节点交换
//每次节点数n-1 (无需砍断操作,只需对数组0~n--调整堆,逻辑上砍断)无需开辟数组存放结果
heapify(tree, i, 0);//调整堆
}
//打印排好的数组
for (vector<int>::iterator it = tree.begin(); it != tree.end(); it++)
cout << *it << " ";
cout << endl;
}
int main()
{
int val = 0;
vector<int> tree;
int n;
cin >> n; //输入节点的数目
// 4 10 3 5 1 2
for (int i = 0; i < n; i++)
{
cin >> val;
tree.push_back(val);
}
//heapify(tree, n, 0); //从第0节点开始成堆
//build_heap(tree,n);
heap_sort(tree, n); //堆排序
system("pause");
return 0;
}