Files
FH/AuD/src/UEB10/HeapSort.java
2023-06-28 21:41:15 +02:00

43 lines
1.2 KiB
Java
Raw Blame History

package UEB10;
public class HeapSort {
// Versickere das Element mit Index pos in dem Teilfeld von Index links bis einschlie<69>lich Index rechts
public static void versickere(int[] array, final int links, int pos, final int rechts) {
int groesster = pos;
int l = 2 * (pos - links) + 1 + links;
int r = 2 * (pos - links) + 2 + links;
if (l <= rechts && array[l] > array[groesster])
groesster = l;
if (r <= rechts && array[r] > array[groesster])
groesster = r;
if (groesster != pos) {
int swap = array[pos];
array[pos] = array[groesster];
array[groesster] = swap;
versickere(array, links, groesster, rechts);
}
}
public static void heapsort(int[] array, final int links, final int rechts) {
int n = rechts - links + 1;
// Heap aufbauen
for (int i = links + n / 2 - 1; i >= links; i--)
versickere(array, links, i, rechts);
// Eines nach dem anderen ein Element aus dem Heap extrahieren
for (int i = rechts; i >= links; i--) {
// Aktuelle Wurzel ans Ende verschieben
int temp = array[links];
array[links] = array[i];
array[i] = temp;
// max heapify auf dem reduzierten Heap aufrufen
versickere(array, links, links, i - 1);
}
}
}