堆排序

利用最小堆将数组从大到小排列 

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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值