堆排序
来源:互联网 发布:淘宝店怎么发布宝贝 编辑:程序博客网 时间:2024/06/04 17:56
利用最小堆将数组从大到小排列
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 randomb = [random.randint(-20, 20) for _ in range(10)] # 在0到100中产生20个随机数print bheap_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;}elsebreak;}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;}
阅读全文
0 0
- 堆及堆排序
- 堆/堆排序特点
- 【二叉堆、堆排序】
- 二叉堆 & 堆排序
- 二叉堆 & 堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆和堆排序
- 堆排序(最大堆)
- 堆和堆排序
- 堆和堆排序
- 堆及堆排序
- 堆和堆排序
- 堆与堆排序
- HTML CSS:Getting Serious with HTML
- 303. Range Sum Query
- 安装NVIDIA显卡驱动+CUDA+CUDNN+NVCAFFE的问题总结
- bzoj 2829 计算几何
- 8.7 约数个数shlqsh 2535
- 堆排序
- vs2015编译mysql-connector-cpp-1.1.9
- Thread的join方法
- USACO JAN14 奶牛冰壶运动 凸包+判定
- 11-SpringBoot——Spring MVC基础-常用注解
- Bootstrap 斜体、文本对齐、缩略图、地址、列表等
- Linux基础知识
- 自定义javascript日历控件
- 【NOIP2011PJ】瑞士轮