iliya785

heapsort

May 21st, 2012
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 0.78 KB | None | 0 0
  1. var
  2.     heap:array[1..100000] of longint;
  3.     i,j,n,m,t:longint;
  4.  
  5. procedure swap(var a,b:longint);
  6. var temp:longint;
  7. begin
  8.   temp:=a;
  9.   a:=b;
  10.   b:=temp;
  11. end;
  12.  
  13. procedure build(i:longint);
  14. var l,r,max:longint;
  15.  begin
  16.    l:=i shl 1;
  17.    r:=l+1;
  18.    max:=i;
  19.    if (l<=n) and (heap[l] > heap[max]) then
  20.       max:=l;
  21.    if (r<=n) and (heap[r] > heap[max]) then
  22.       max:=r;
  23.    if (max <> i) then
  24.     begin
  25.      swap(heap[i],heap[max]);
  26.      build(max);
  27.     end;
  28.  end;
  29.  
  30. procedure heapsort(n:longint);
  31.  begin
  32.    swap(heap[1],heap[n]);
  33.    dec(n);
  34.    build(1);
  35.  end;
  36.  
  37. Begin
  38.   read(n);
  39.   for i:=1 to n do
  40.     read(heap[i]);
  41.   for i:=n shr 1 downto 1 do
  42.     build(i);
  43.   for i:=1 to n do
  44.     heapsort(n-i+1);
  45.   for i:=1 to n do
  46.     write(heap[i],' ');
  47. end.
Advertisement
Add Comment
Please, Sign In to add comment