#include "sortieren.h" #include using namespace std; void tausche(int & a, int & b) { int h=a; a=b; b=h; } void MinimumSort(int tosort[], const int l, const int r) { int mindex; for(int i=l;itosort[j+1]) tausche(tosort[j],tosort[j+1]); } void InsertionSort(int tosort[], const int l, const int r) { for(int i=l+1;i<=r;i++) for(int j=i;j>l;j--) if (tosort[j] Stichwort: Tail-Rekursion // -> höchstens logarithmisch statt linear viele Variablen auf dem Stack } } int *kopie; // Array für Kopie in MergeSort int *mtosort; // modulweit bekanntes Array, um Übergabe bei der Rekursion zu sparen void MergeSortRek(const int, const int); // Vorwärtsdeklaration void MergeSort(int tosort[], const int l, const int r) { // sortiert tosort[l..r] mtosort=tosort; kopie=new int[(r-l)/2+1]; // maximal benötigter Zusatzspeicher MergeSortRek(l,r); delete kopie; } void MergeSortRek(const int l, const int r) { // sortiert tosort[l..r] if (ltosort[r]) { if (tosort[l]>tosort[v]) { // Element sinkt links weiter tausche(tosort[l],tosort[v]); v=l; l=2*v; r=l+1; } else break; // Element sinkt nicht weiter } else { if (tosort[r]>tosort[v]) { // Element sinkt rechts weiter tausche(tosort[r],tosort[v]); v=r; l=2*v; r=l+1; } else break; // Element sinkt nicht weiter } } else { // l=n und das linke Kind ist ein Blatt if (tosort[l]>tosort[v]) tausche(tosort[l],tosort[v]); break; } } } int *heap; // modulweit bekanntes Array für Heapsort // für die Praxis besser: sink als Bottom-up-Variante void sink(const int i, const int n) { // lässt das Element heap[i] // im heap[1..n] so absinken, dass die Heapeigenschaft erfüllt ist int v=i; int l,r; int h1,h2; // bestimme Blatt des Einsinkpfades while (2*v heap[r]) { // sinkt in Richtung des größeren Kindes v=l; } else { v=r; } } if (2*v==n) { v=n; // Einzelkind } // v ist jetzt das Blatt des Einsinkpfades // im Einsinkpfad soweit nötig wieder aufsteigen while (heap[v] < heap[i]) { v=v/2; } // Elemente auf dem Pfad bis i rotieren h1=heap[v]; heap[v]=heap[i]; v=v/2; while (v > i) { h2=h1; h1=heap[v]; heap[v]=h2; v=v/2; } heap[i]=h1; } void HeapSort(int tosort[], const int l, const int r) { // sortiert tosort[l..r] heap=tosort+l-1; // heap zeigt jetzt auf das Element links vom linken Rand // auf heap[0] darf nicht zugegriffen werden! int n=r-l+1; // soviel Elemente werden sortiert // der zu sortierende Bereich steht jetzt in heap[1..n] // Heapaufbau for(int i=n/2;i>=1;i--) { sink(i,n); } // Sortierphase for(int i=n;i>1;i--) { tausche(heap[i],heap[1]); sink(1,i-1); } }