Previous Contents Next

2   Sortieren

Literatur: Kapitel 7 und 8 aus [CLR90]. Knuth [Knu73b] enthält mehr über Sortieren als man wissen will. Heapsort stammt von Williams [Wil64], Quicksort von Tony Hoare [Hoa62]
Inhalt Heaps ·Heapsort ·Quicksort
Heap-Datenstruktur


Implementierung: Heaps als Array


Heapsort: Aufbau
Einfügen in den Heap




Heapify (A, i)                  
  l := Left(i); r := Right(i);  // Left(i), Right(i) are heaps   

  if l <= heapsize(A) and A[l] > A[i]
     then largest := l  else largest := i;
  if r <= heapsize(A) and  A[r] > A[largest]
     then largest := r;

  if largest != i                 // Verletzung der Heapbedingung?
     then exchange (A[i] , A[largest]);
          Heapify(A, largest);





Aufbau des Heaps


Build-Heap(A)  
  heapsize[A]  := length[A];
  for i= floor(length(A)/2)) downto 1
      do 
         heapify(A,i);





Heapsort






Heapsort(A)

   build_heap(A);
   for i = length(A) downto 2
   do  exchange A[1] A[i];
       heapsize[A] := heapsize[A] - 1;
       Heapify(A,1);



Quicksort


Quicksort (2)




(* $Id: quicksort.ml,v 1.6 1999/11/11 10:43:28 ms Exp $ *)

open Basic;;
open Sort;;

module QuicksortFun (E: ORDERED) : (SORT with type elem = E.t) =
    struct
      type elem = E.t 
     
      let rec filter p l = match l with 
     []     -> []
      | x :: tl ->  
   if   (p x) 
   then  x::(filter p tl)
   else  filter p tl
     
      let rec sort (l : elem list) =   match l with  
        []  -> []
      | x :: tl  -> 
   sort (filter (function y -> E.lt(y,x)) tl)
   @ [x] @                                     (* Pivot *)
   sort (filter (function y -> E.geq(y,x)) tl)
    end







Quicksort mit arrays (1)




Quicksort(A,p,r)
if  p < r 
    then   q := Partition(A,p,r)   
           Quicksort(A,p,q);
           Quicksort(A,q+1,r);



Quicksort mit arrays: Partitionieren


I1 A[i'] £ x £ A[j'] für alle i'< i, j' > j.
I2 A[i'] £ x £ A[j'] für alle i'£ i, j' ³ j.




Partition(A,p,r)                      /* p <= r         */
  x := A[p];
  i := p-1;
  j := r+1;
 
  while true                          /* Invariante I_2 */
  do     repeat j := j-1
           until A[j] <= x;
         repeat i := i+1
           until A[i] >= x;
         if   i < j                   /* Invariante I_1 */
         then exchange A[i] <-> A[j]  /* Invariante I_2 */
         else return   j;             /* j <= i         */
  od;
  
         



Analyse von Quicksort: worst case
Analyse von Quicksort: best case


January 23, 2001
Previous Contents Next