Friday, April 11, 2014

Bubble Sorting in Java

Bubble sorting sorts the array in-place bubbling up the largest value.
Complexity:
Worst case - O(n^2); average case - O(n^2); best case - O(n)

Visualization: (src. Wiki)


package org.algorithms.sorting;
import java.util.Arrays;

public class BubbleSortDemo {
public static void doBubbleSort(int[] args) {
        boolean swapped;
        do {
            swapped = false;
            for (int i=1; i<args.length; i++)
                if (args[i-1] > args[i]) {
                    int temp = args[i - 1];
                    args[i - 1] = args[i];
                    args[i] = temp;
                    swapped = true;
                }
        } while(swapped);
    }

    public static void main(String[] args) {
        int[] numbers = {5,4,3,2,1,6};
        System.out.println("Original: " + Arrays.toString(numbers));
        doBubbleSort(numbers);
        System.out.println("Sorted: " + Arrays.toString(numbers));
    }

}

Output:
Original: [5, 4, 3, 2, 1, 6]
Sorted: [1, 2, 3, 4, 5, 6]

No comments:

Post a Comment

Liked or hated the post? Leave your words of wisdom! Thank you :)