Monday, February 9, 2009

Bubble Sorting An Array

Bubble sorting an array A[0, 1, 2, ..., n-1]

01 BubbleSort(A[0, 1, 2, ..., n-1])
02 i <- 0 03 repeat 04 exch <- False 05 for (j <- 0) to (n-2-i) do 06 if A[j] > A[j+1] then
07 exchange A[j] <-> A[j+1]
08 exch <- True
09 end if
10 end for
11 i <- i+1
12 Until exch = False

Click here for explanation on what is bubble sort?

2 comments:

  1. Here is a nice visual explanation of Bubble sort from YouTube
    http://www.youtube.com/watch?v=Jdtq5uKz-w4

    ReplyDelete
  2. //// Java Program for Bubble Sort ////

    class BubbleSort {
    public static void main(String[] args) {
    long start = System.currentTimeMillis();
    System.out.println("----- Main Starts over here -----");

    String number1 = "101110101101011000000";
    char[] number = number1.toCharArray();
    System.out.println("Before Sorting:-");
    for (int i = 0; i < number.length; i++) {

    System.out.print(number[i]);
    }
    System.out.println();
    System.out.println("After Sorting:-");
    char temp;
    boolean fixed = false;
    while (fixed == false) {
    fixed = true;

    for (int i = 0; i < number.length - 1; i++) {

    if (number[i] > number[i + 1]) {
    temp = number[i + 1];
    number[i + 1] = number[i];
    number[i] = temp;
    fixed = false;
    }

    }

    }
    fixed = true;

    for (int i = 0; i < number.length; i++) {
    System.out.print(number[i]);

    }

    ReplyDelete