zoukankan      html  css  js  c++  java
  • Heapsort

    Chapter 6: Heapsort

    Chapter 6: Heapsort

    Overview

    In this chapter, we introduce another sorting algorithm. Like merge sort, but unlike insertion sort, heapsort's running time is O(n lg n). Like insertion sort, but unlike merge sort, heapsort sorts in place: only a constant number of array elements are stored outside the input array at any time. Thus, heapsort combines the better attributes of the two sorting algorithms we have already discussed.

    Heapsort also introduces another algorithm design technique: the use of a data structure, in this case one we call a "heap," to manage information during the execution of the algorithm. Not only is the heap data structure useful for heapsort, but it also makes an efficient priority queue. The heap data structure will reappear in algorithms in later chapters.

    We note that the term "heap" was originally coined in the context of heapsort, but it has since come to refer to "garbage-collected storage," such as the programming languages Lisp and Java provide. Our heap data structure is not garbage-collected storage, and whenever we refer to heaps in this book, we shall mean the structure defined in this chapter.

     

    我的代码:

     

    代码
    const n=10;
    type arr=array[1..n] of integer;
    var i,t:integer;
    a:arr;
    procedure heap(var a:arr;l,r:integer);
    var i,j,k,t:integer;
    begin
    i:
    =2*l;j:=i+1;
    if (i<=r ) and (a[i]>a[l]) then k:=i
    else k:=l;
    if (j<=r ) and (a[j]>a[k]) then k:=j;

    if k<>l then begin
    t:
    =a[l];a[l]:=a[k];a[k]:=t;
    heap(a,k,r);
    end;
    end;
    begin
    for i:=1 to n do read(a[i]);
    for i:=n div 2 downto 1 do heap(a,i,n);
    for i:=1 to n-1 do
    begin
    write(a[
    1],' ');
    t:
    =a[1];
    a[
    1]:=a[n-i+1];
    a[n
    -i+1]:=t;
    heap(a,
    1,n-i);
    end;
    writeln(a[
    1]);
    end.

    or

    代码
    program duipx;
    const n=8;
    type arr=array[1..n] of integer;
    var a:arr;i:integer;
    procedure sift(var a:arr;l,m:integer);
    var i,j, t:integer;
    begin
    i:
    =l;j:=2*i;t:=a[i];
    while j<=m do
    begin
    if (j<m) and (a[j]>a[j+1]) then j:=j+1;
    if t>a[j] then
    begin a[i]:=a[j];i:=j;j:=2*i; end
    else exit;
    a[i]:
    =t;
    end;

    end;
    begin
    for i:=1 to n do read(a[i]);
    for i:=(n div 2) downto 1 do
    sift(a,i,n);
    for i:=n downto 2 do
    begin
    write(a[
    1]:4);
    a[
    1]:=a[i];
    sift(a,
    1,i-1);
    end;
    writeln(a[
    1]:4);
    end.
  • 相关阅读:
    转载:div和flash层级关系问题
    转载:页面加载swf插件:swfobject
    C++ code:浮点数的比较(Floating-Pointing Number Comparison)
    Deep Learning系统实训之三:卷积神经网络
    C++ code:指针类型(pointer types)
    Linear Algebra(未完待续)
    Deep Learning系统实训之二:梯度下降原理
    C++ code:向量操作之添加元素
    Deep Learning系统实训之一:深度学习基础知识
    机器学习与优化关系、凸集、凸函数简介
  • 原文地址:https://www.cnblogs.com/nbalive2001/p/1873351.html
Copyright © 2011-2022 走看看