BubbleSort.java

import java.io.*;

public class BubbleSort {
  // Beispielprogramm für Bubblesort-Algorithmus
  
  public static void main(String[] args) throws IOException {
    // erzeugt ein Array von Zufallszahlen und gibt es sortiert aus
    
    BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));
    
    // Größe des Arrays erfragen
    String s;    // String für eingegebene Zeile
    System.out.println("Anzahl der zu sortierenden Werte eingeben:");
    s = in.readLine();
    int anzahl = Integer.parseInt(s);
    // abfragen, ob Liste ausgegeben werden soll
    System.out.println("Soll die sortierte Liste ausgegeben werden (j/n):");
    s = in.readLine();
    boolean mitAusgabe = false;
    if (s.compareTo("j") == 0) {
      mitAusgabe = true;
    }
    
    // erzeuge die Liste
    double[] liste = new double[anzahl];
    
    // fülle die Liste mit Zufallszahlen
    for (int i = 0; i < anzahl; i++) {
      liste[i] = Math.random();
    }
    
    // sortiere die Liste und miss die benötigte Zeit
    long timeBefore = System.currentTimeMillis();
    sort(liste);
    long timeAfter = System.currentTimeMillis();
    double timeSpent = (timeAfter - timeBefore)/1000.0;  // in s
    System.out.println("Zeit zum Sortieren: " + timeSpent + "s");
    
    // gib die Liste aus, falls gewünscht
    if (mitAusgabe) {
      for (int i = 0; i < anzahl; i++) {
        System.out.println(liste[i]);
      }
    }
  }
  
  // Sortier-Routine nach dem Bubblesort-Algorithmus
  static void sort(double[] a) {
    boolean nochmal = true;
    
    while (nochmal) {
      // laufe solange durch das Array, bis keine Vertauschungen mehr nötig waren
      nochmal = false;
      for (int i = 0; i < a.length - 1; i++) {
        if (a[i] > a[i + 1]) {
          vertausche(a, i, i + 1);
          nochmal = true;
        }
      }
    }
  }
   
  // vertausche a[i] und a[j]
  static void vertausche(double[] a, int i, int j) {
    double temp = a[i];
    a[i] = a[j];
    a[j] = temp;
  }
}