Sortieren
Aus EINI
Das Sortieren ist ein Standardproblem der Informatik
Inhaltsverzeichnis
Sortieralgoritmen
Bubblesort
bubbleSort(int[] A)
for(int n = A.length; n > 1; n--) {
for (int i = 0; i < n-1; i++) {
if (A[i] > A[i+1]){
int swap = A[i];
A[i] = A[i+1];
A[i+1] = swap;
}
}
}
Heapsort
public static void heapSort(int[] a) {
generateMaxHeap(a);
for( int i = a.length - 1; i > 0; i--) {
tausche(a, i, 0);
heapify(a, 0, i);
}
}
public static void generateMaxHeap(int[] a) {
for(int i = (a.length / 2) - 1; i >= 0; i--) {
heapify(a, i, a.length);
}
}
public staitc void heapify(int[] a, int k, int anzahlKnoten) {
int lsNR = 2*k, //Nummer des linken Sohns
rsNR = 2*k+1, //Nummer des rechten Sohns
selSohn; //Nummer des selektierten Sohns
if (lsNr <= anzahlKnoten && rsNr > anzahlKnoten) { //es gibt keinen rechten Sohn
if (heapFeld[lsNr] < heapFeld[k] {
tausche(k, lsNr);
}
}
else if (rsNr <= anzahlKnoten) {
selSohn = (heapFeld[lsNr] < heapFeld[rsNr] ? lsNr : rsNr);
// Wähle den Sohn mit der kleineren Markierung aus.
// Bei Gleichheit wähle den rechten Sohn.
if (heapFeld[selSohn] < heapFeld[k]) { //Heap-Bedingung verletzt
tausche(k, selSohn);
heapify(selSohn);
}
}
}
public static void tausche(int[] a, int i, int j){
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
Insertionsort
Insertionsort(int[] A)
for (int i = 1; i < A.length; i++){
int insort = A[i];
int j = i;
while (j > 1 && A[i-j] > insort){
A[j] = A[j-1];
j--;
}
A[j] = insort;
}