Skip to content

Instantly share code, notes, and snippets.

@J0B10
Last active November 23, 2020 11:26
Show Gist options
  • Save J0B10/70784d76cd68b85f1db96e1f12cee83c to your computer and use it in GitHub Desktop.
Save J0B10/70784d76cd68b85f1db96e1f12cee83c to your computer and use it in GitHub Desktop.
Einfache Sortierverfahren

Bubblesort

Vorgehensweise

  • Das Array wird wiederholt von links nach rechts durchlaufen.
  • Steht eine größere Zahl vor einer kleineren Zahl, so werden die beiden Zahlen miteinander vertauscht. Damit steht am Ende des 1.Durchlaufs das größte Element ganz rechts.
  • Wiederhole solange Arraydurchläufe, bis das ganze Array sortiert ist.

Komplexität

  • Bubblesort benötigt ungefähr n2/2 Vergleiche (immer) und n2/4 Austauschoperationen (average case).
  • Landau-Notation: O(n2)

Schema

Selectionsort

Vorgehensweise

Von links aus wird nach und nach der sortierte Bereich vergrößert:

  • Im noch nicht sortierten Bereich wird jeweils der kleinste Wert gesucht.
  • Der kleinste Wert wird dann mit dem ersten Element des noch nicht sortierten Bereichs vertauscht.

Komplexität

  • Selectionsort benötigt ungefähr n2/2 Vergleiche und n Austauschoperationen.
  • Landau-Notation: O(n2)

Schema

Insertionsort

Vorgehensweise

  • Von links aus wird nach und nach der sortierte Bereich vergrößert.
  • In jedem Durchlauf wird das erste Element des noch nicht sortierten Bereichs an die richtige Position in den links davon liegenden sortierten Bereich einsortiert.
  • Optimierungsmöglichkeit (binary insertion sort): Einfügeposition mit binärer Suche bestimmen – spart Vergleiche.

Komplexität

  • Insertionsort benötigt im Durchschnitt ungefähr n2/4 Vergleiche und n2/8 Austauschoperationen (bzw. n2/4 Zuweisungen), im ungünstigsten Fall doppelt so viele.
  • Landau-Notation: O(n2)

Schema

import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Sort {
private static final Scanner SC = new Scanner(System.in);
public static void main(String[] args) {
int[] unsorted = testArray();
int[] bubble = unsorted.clone();
int[] selection = unsorted.clone();
int[] insertion = unsorted.clone();
Instant start, end;
start = Instant.now();
bubbleSort(bubble);
end = Instant.now();
System.out.println("Bubble sort took " + Duration.between(start, end));
start = Instant.now();
selectionSort(selection);
end = Instant.now();
System.out.println("Selection sort took " + Duration.between(start, end));
start = Instant.now();
insertionSort(insertion);
end = Instant.now();
System.out.println("Insertion sort took " + Duration.between(start, end));
System.out.println("Unsorted: " + Arrays.toString(unsorted));
System.out.println("Bubble sort: " + Arrays.toString(bubble));
System.out.println("Selection sort: " + Arrays.toString(selection));
System.out.println("Insertion sort: " + Arrays.toString(insertion));
}
private static int[] testArray() {
System.out.print("Min: ");
int min = SC.nextInt();
System.out.print("Max: ");
int max = SC.nextInt();
System.out.print("Size: ");
int size = SC.nextInt();
Random random = new Random();
int[] numbers = new int[size];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextInt(max - min + 1) + min;
}
return numbers;
}
/**
* Sorts the given array using <b>bubble sort</b> algorithm.
* <p>
* Sorted area on the right is increased in size.
* The first element of unsorted area is compared to the next one and swapped if it is bigger.
* Then the bigger one is compared with the nex one and again swapped.
* Once this has iterated once through the unsorted area it starts again on the left side and repeats
* till all elements are sorted. That way bubbles of similar elements travel slowly from left to right.
* <p>
* Avg. n²/2 (always) comparisons and n²/4 (average, depends on entropy) swaps.
* <p>
* Abort for presorted arrays can be implemented.
*/
public static void bubbleSort(int[] data) {
for (int leftBoundary = data.length; leftBoundary > 0; leftBoundary--) {
boolean abort = true;
for (int i = 1; i < leftBoundary; i++) {
if (data[i - 1] > data[i]) {
int temp = data[i];
data[i] = data[i - 1];
data[i - 1] = temp;
abort = false;
}
}
if (abort) return;
}
}
/**
* Sorts the given array using <b>selection sort</b> algorithm.
* <p>
* Sorted area on the left is increased in size.
* The unsorted area on the right is searched through, looking for the smallest element.
* When all elements are checked the smallest element is selected and swapped with the first of the unsorted area.
* That way the sorted area increases its size till it covers the entire array.
* <p>
* Avg. n²/2 comparisons and n swaps.
* <p>
* Presorted arrays take the same time as unsorted ones.
*/
public static void selectionSort(int[] data) {
for (int sorted = 0; sorted < data.length; sorted++) {
int smallestPos = sorted;
for (int i = sorted; i < data.length; i++) {
if (data[i] < data[smallestPos]) {
smallestPos = i;
}
}
int tmp = data[sorted];
data[sorted] = data[smallestPos];
data[smallestPos] = tmp;
}
}
/**
* Sorts the given array using <b>insertion sort</b> algorithm.
* <p>
* Sorted area on the left is increased in size. The first element of unsorted area is picked
* and compared with the elements in the sorted area from right to left.
* All elements that are bigger than the picked are shifted one to the right.
* <p>
* Avg. n²/4 comparisons and n²/8 swaps, max. doubled amount.
* <p>
* Detects and aborts for presorted arrays.
*/
public static void insertionSort(int[] data) {
for (int i = 1; i < data.length; i++) {
int value = data[i];
int newPos = i;
for (newPos = i; newPos > 0; newPos--) {
if (data[newPos - 1] > value) {
data[newPos] = data[newPos - 1];
} else {
break;
}
}
data[newPos] = value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment