堆排序之递归排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Nliki/article/details/89002188
#include "stdafx.h";
#include <iostream>;
using std::cout;
using std::cin;
using std::endl;
void recSort(int[],int,int);

int main()
{

	int nums[] = { 1,2,3,4,5,6,7,8,9 };
	int nums_length = sizeof nums / sizeof(int);
	cout << "堆排序之前: ";
	for (int i = 0; i < nums_length; i++)
	{
		cout << nums[i] << " ";
	}
	cout << endl;
	for (int i = nums_length / 2; i >= 0; i--)
	{
		recSort(nums,i,nums_length);
	}
	cout << "堆排序之后: ";
	for (int i = 0; i < nums_length; i++)
	{
		cout << nums[i] <<" ";
	}
	cout << endl;
	/*cin.get();*/
	return 0;
}
void recSort(int *a, int node, int size) {
	int left = 2 * node;
	int right = 2 * node + 1;
	int max = node;
	if (left<size&&a[left]>a[max]) {
		max = left;
	}
	if (right<size&&a[right]>a[max]) {
		max = right;
	}
	if (max != node) {
		std::swap(a[max], a[node]);
		recSort(a,max,size);
	}
}

输入结果

猜你喜欢

转载自blog.csdn.net/Nliki/article/details/89002188