4d15b881ec1a21d45e30976845468090298f9553
BubbleSort.md
| ... | ... | @@ -0,0 +1,52 @@ |
| 1 | +# Bubble Sort |
|
| 2 | + |
|
| 3 | +**Bubble Sort** ist ein einfacher Sortieralgorithmus, der wiederholt benachbarte Elemente vergleicht und vertauscht, bis das Array sortiert ist. Er ist besonders für Lehrzwecke geeignet, aber aufgrund seiner 'O(n^2)'-Komplexität ungeeignet für große Datenmengen. |
|
| 4 | + |
|
| 5 | +## Funktionsweise |
|
| 6 | +Der Algorithmus durchläuft das Array mehrfach. Bei jedem Durchlauf „blubbert“ das größte unsortierte Element an seine korrekte Position. Durch frühzeitiges Abbrechen, falls kein Tausch erfolgte, kann die Effizienz im besten Fall auf 'O(n)' verbessert werden. |
|
| 7 | + |
|
| 8 | + |
|
| 9 | +Quelle[^1] |
|
| 10 | + |
|
| 11 | + |
|
| 12 | +## Java-Implementierung (optimiert) |
|
| 13 | +```java |
|
| 14 | +public class BubbleSort { |
|
| 15 | + public static void bubbleSort(int[] arr) { |
|
| 16 | + int n = arr.length; |
|
| 17 | + boolean swapped; |
|
| 18 | + for (int i = 0; i < n - 1; i++) { |
|
| 19 | + swapped = false; |
|
| 20 | + for (int j = 0; j < n - i - 1; j++) { |
|
| 21 | + if (arr[j] > arr[j + 1]) { |
|
| 22 | + // Tausche Elemente |
|
| 23 | + int temp = arr[j]; |
|
| 24 | + arr[j] = arr[j + 1]; |
|
| 25 | + arr[j + 1] = temp; |
|
| 26 | + swapped = true; |
|
| 27 | + } |
|
| 28 | + } |
|
| 29 | + if (!swapped) break; // Frühzeitiger Abbruch |
|
| 30 | + } |
|
| 31 | + } |
|
| 32 | + |
|
| 33 | + public static void main(String[] args) { |
|
| 34 | + int[] data = {64, 34, 25, 12, 22, 11, 90}; |
|
| 35 | + bubbleSort(data); |
|
| 36 | + System.out.print("Sortiert: "); |
|
| 37 | + for (int i : data) System.out.print(i + " "); |
|
| 38 | + } |
|
| 39 | +} |
|
| 40 | +``` |
|
| 41 | + |
|
| 42 | +### Eigenschaften |
|
| 43 | +| Merkmal | Wert | |
|
| 44 | +|--------|------| |
|
| 45 | +| **Best-Case** | 'O(n)' | |
|
| 46 | +| **Worst-Case** | 'O(n^2)' | |
|
| 47 | +| **Speicher** | 'O(1)' | |
|
| 48 | +| **Stabil** | Ja | |
|
| 49 | + |
|
| 50 | + |
|
| 51 | + |
|
| 52 | +[^1]: https://informatik-bg.de/jg2-bpe-7-2-sortier-und-suchalgorithmen/bubble-sort |
|
| ... | ... | \ No newline at end of file |
bubblesort.png
| ... | ... | Binary files /dev/null and b/bubblesort.png differ |