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.
  • 相关阅读:
    Delphi下Treeview控件基于节点编号的访问
    oracle的conn / as sysdba是以sys还是system用户登录呢?
    delphi 字母加数字如何自增??比如0A--0Z,1A--1Z一直到9A--9Z 请赐教
    ORACLE_HOME要怎么配置?
    sqlplus / as sysdba 详解
    oracle 11G数据库实例增加内存
    SQL在字符串中取出最长数字子序列
    delphi 全局变量的定义与初始化赋值
    Delphi公用函数单元
    Dapper的正确使用姿势
  • 原文地址:https://www.cnblogs.com/nbalive2001/p/1873351.html
Copyright © 2011-2022 走看看