C ++ heap sort

Heap sort means for sorting algorithm using such a stack data structure, the time complexity is On * log2 (n), and were nearly quicksort.

Heapsort

The heap is a complete binary tree similar structure, where we will be seen as a complete array of a binary tree structure, first create maximum heap, not only will all the data reordering heap, after entering the loop, each exchange a [1] and a [i] value, because the value of a [1] is the maximum value of the current sequence, it will be a [1] into the end, and then for 1 ~ - cohort (I 1) consisting of the maximum heap adjustment, both the ends of the stack adjusted child node, the child node is always less than that parent. Such sorting algorithm is over, the code will naturally written out.

(PS: NR is the upper limit of the number of elements of the array)

# include <cstdio>
# include <iostream>
# include <cmath>
# include <cstring>
# include <algorithm>
using namespace std;

# define FOR(i, a, b) for(int i = a; i <= b; i++)
# define _FOR(i, a, b) for(int i = a; i >= b; i--)

const int NR = 100000;

int n;
int a[NR + 10];

void maxHeapify(int first, int last){
	int dad = first, son = first * 2;
	if(son > last) return;
	if(son + 1 <= last && a[son] < a[son + 1]) son++;
	if(a[dad] > a[son]) return;
	swap(a[dad], a[son]);
	maxHeapify(son, last);
}

int main()
{
	scanf("%d", &n);
	FOR(i, 1, n) scanf("%d", &a[i]);
	_FOR(i, n / 2, 1) maxHeapify(i, n);
	_FOR(i, n, 2){
		swap(a[1], a[i]);
		maxHeapify(1, i - 1);
	}
	FOR(i, 1, n) printf("%d ", a[i]);
	puts("");
	return 0;
}

God Bless You For Ever!

Published 33 original articles · won praise 47 · views 10000 +

Guess you like

Origin blog.csdn.net/SkeletonKing233/article/details/100177681