利用最小堆将数组从大到小排列
Python代码:
# -*- coding: utf-8 -*-
'''
堆排序
'''
# 从上往下调整堆,使得堆变成最小堆
def filter_down(array, beg, end):
current, child = beg, 2*beg + 1
temp = array[current]
while child <= end:
if child < end and array[child] > array[child + 1]:
child += 1
if array[child] < temp:
array[current] = array[child]
current, child = child, 2*child + 1
else:
break
array[current] = temp
# 堆排序,排序后的数组从大到小排列
def heap_sort(array):
m = len(array) - 1
for i in range(int((m-1)/2), -1, -1):
filter_down(array, i, m)
array[0], array[m] = array[m], array[0]
for j in range(m - 1, 0, -1):
filter_down(array, 0, j)
array[0], array[j] = array[j], array[0]
import random
b = [random.randint(-20, 20) for _ in range(10)] # 在0到100中产生20个随机数
print b
heap_sort(b)
print b
C++代码:
void swap(double &a, double &b) {
double t = a;
a = b;
b = t;
}
void filter_down(double* array, int beg, int end) {
double temp = array[beg];
int current = beg, child = 2 * beg + 1;
while (child <= end) {
if (child < end && array[child + 1] < array[child])
child += 1;
if (temp > array[child]) {
array[current] = array[child];
current = child;
child = 2 * child + 1;
}
else
break;
}
array[current] = temp;
}
#include <iostream>
using namespace std;
#include <string>
using std::string;
#include "heap_sort.h"
int main() {
const int N = 10;
double a[N] = {-10, -8, -18, 4, 17, 0, -12, -14, 10, -10};
for (int i = (int)((N - 2) / 2); i >= 0; --i) filter_down(a, i, N - 1);
for (int i = N - 1; i > 0; --i) {
filter_down(a, 0, i);
swap(a[0], a[i]);
}
for (int i = 0; i < N; ++i) {
cout << a[i] << '\t';
}
cout << endl;
string s;
for (cin >> s; s != "c"; cin >> s)
continue;
return 0;
}