Java Bubble Sort Algorithm Tutorial

Introduction

Bubble sort is the slowest sorting algorithm. Its implementations are there since 1956. Bubble sort is implemented by comparing each data element in the list with all the next data elements in the list and keep on swapping the data elements if they out of order. This process is repeated till entire data set is sorted. This algorithm has all complexity O(N^2) for best, worst and average runtime cases. Obviously bubble sort is most inefficient sorting algorithm as compared to its counterparts Shell sort, selection sort and insertion sort. The main advantages of this algorithm is that it is extremely easier to implement. The biggest disadvantage is its inefficiency.

How It Works

Bubble Sort or Sinking Sort is a simple sorting algorithm. Repeatedly Take an element of the unsorted List or Array and compare it with its adjacent element. Swap the elements if they are not in order. It uses nested loops. The element A[0] is compared with A[1], Element A[1] with A[2], and so on until the List or Array is sorted.

FillArray.java

import java.util.Random;

/**
 * Class will fill a given array of size N, in a range
 * of integers Min-Max
 *
 * @author CodingHelpLine
 * Web: codinghelpline.org
 */
public class FillArray {
   
    // Delcare Random object at class level
    private static Random random = new Random();
   
    /**
     * Fill an array of given size with given range of integers.
     *
     * @param array
     * @param min
     * @param max
     */
    public void fillArray(int array [], int min, int max) {
       
        // fill the array
        // iterate using for loop size time
        for(int counter = 0; counter < array.length; counter++) {
            array[counter] = generateRandom(min, max);
        }
    }
   
    /**
     * Print the array
     *
     * @param array
     */
    public void printArray(int array []) {
        // loop to pirnt 10 elements on a line
        for(int counter = 0; counter < array.length; counter++) {
            System.out.printf("%5d", array[counter]);
           
            // New line after every 10 elements
            if((counter + 1) % 10 == 0) {
                System.out.println();
            }
        }
    }

    /**
     * Generate Random number in a given range.
     *
     * @param min
     * @param max
     * @return random number
     */
    public int generateRandom(int min, int max) {
        return random.nextInt(max - min) + min;
    }
   
    /**
     * Fill the array with sequence from 1 to N
     *
     * @param array
     */
    public void fillArray(int array []) {
       for(int i=0; i<array.length; i++) {
           array[i] = i + 1;  // 1 to N
       }
    }
   
}

BubbleSort.java

import java.util.Arrays;
/**
 * Implementation of Bubble Sort Algorithm with Time Complexity and
 * keep track of comparisons and swaps.
 *
 *
 * @author CodingHelpLine
 * Web: codinghelpline.org

 */
public class BubbleSort {
   
    // class fields
    private int array []; // to store elements
    private int numSwaps; // Number of Swaps to count
    private int numComparisons; // number of comparisons;
    private long startTime;     // Start time of algorithm
    private long endTime;       // End time of algorithm
   
    /**
     * Constructor
     *
     * @param array
     */
    public BubbleSort(int array []) {
        this.array = Arrays.copyOf(array, array.length);
        numSwaps = 0;
        numComparisons =0 ;
    }
   
    public int getSwaps() {
        return this.numSwaps;
    }
   
    public int getComparisons() {
        return this.numComparisons;
    }
   
    public long getTime() {
        return this.endTime - this.startTime;
    }
   
    /**
     * Bubble Sort Algorithm
     */
    public void bubbleSort() {
       
        // start time
        this.startTime = System.currentTimeMillis();
       
        // for passes
        for(int i=0; i<array.length; i++) {
           
            // for comparison and swapping
            for(int j=0; j<array.length - i - 1; j++) {
               
                // count comparisons
                this.numComparisons++;
               
                // Compare adjacent elements
                if(array[j] > array[j+1]) {
                   
                    // swap
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                   
                    // increase swap
                    this.numSwaps++;
                }
            }
        }
       
        // End time
        this.endTime = System.currentTimeMillis();
    }
   
    public int [] getArray() {
        return this.array;
    }
}

BubbleSortTest.java

/**
 * Client code to test the Bubble Sort Algorithm with different data sets.
 *
 * @author CodingHelpLine
 * Web: codinghelpline.org
 */
public class BubbleSortTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
        // 3 things
        final int MIN = 1;
        final int MAX = 100;
        final int SIZE = 10;
       
        // fill the array
        FillArray fillArray = new FillArray();
       
        // declare arrays
        int arrayOne [] = new int[SIZE];
       
        // FILL IT
        //fillArray.fillArray(arrayOne, MIN, MAX);
        fillArray.fillArray(arrayOne);
        // Bubble sort Object
        BubbleSort bubbleSort = new BubbleSort(arrayOne);
       
        // lets print it
        System.out.println("Unsorted Array:");
        fillArray.printArray(bubbleSort.getArray());
       
        // Call function to sort
        bubbleSort.bubbleSort();
       
        System.out.println("\nSorted Array:");
        fillArray.printArray(bubbleSort.getArray());
       
        System.out.println("\nStatistics:");
        System.out.printf("Number of comparisions: %d%n", bubbleSort.getComparisons());
        System.out.printf("Number of Swaps: %d%n", bubbleSort.getSwaps());
        System.out.printf("Time Taken to Sort: %d m/s%n", bubbleSort.getTime());
 
        System.out.println("\nOptimized Bubble Sort:");
        // Bubble sort Object
        OptimizedBubbleSort sort = new OptimizedBubbleSort(arrayOne);
       
        // lets print it
        System.out.println("Unsorted Array:");
        fillArray.printArray(sort.getArray());
       
        // Call function to sort
        sort.bubbleSort();
       
        System.out.println("\nSorted Array:");
        fillArray.printArray(sort.getArray());
       
        System.out.println("\nStatistics:");
        System.out.printf("Number of comparisions: %d%n", sort.getComparisons());
        System.out.printf("Number of Swaps: %d%n", sort.getSwaps());
        System.out.printf("Time Taken to Sort: %d m/s%n", sort.getTime());
    }
}

OptimizedBubbleSort.java

import java.util.Arrays;

/**
 * Optimized Implementation of Bubble Sort with Bench Marking
 *  
 * @author CodingHelpLine
 * Web: codinghelpline.org

 */
public class OptimizedBubbleSort {
        // class fields
    private int array []; // to store elements
    private int numSwaps; // Number of Swaps to count
    private int numComparisons; // number of comparisons;
    private long startTime;     // Start time of algorithm
    private long endTime;       // End time of algorithm
   
    /**
     * Constructor
     *
     * @param array
     */
    public OptimizedBubbleSort(int array []) {
        this.array = Arrays.copyOf(array, array.length);
        numSwaps = 0;
        numComparisons =0 ;
    }
   
    public int getSwaps() {
        return this.numSwaps;
    }
   
    public int getComparisons() {
        return this.numComparisons;
    }
   
    public long getTime() {
        return this.endTime - this.startTime;
    }
   
    /**
     * Bubble Sort Algorithm
     */
    public void bubbleSort() {
       
        boolean flag = true;
       
        // start time
        this.startTime = System.currentTimeMillis();
       
        // for passes
        for(int i=0; i<array.length && flag; i++) {
           
            // mean no more comparison or swap needed
            flag = false;
           
            // for comparison and swapping
            for(int j=0; j<array.length - i - 1; j++) {
               
                // count comparisons
                this.numComparisons++;
               
                // Compare adjacent elements
                if(array[j] > array[j+1]) {
                   
                    flag = true;
                   
                    // swap
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                   
                    // increase swap
                    this.numSwaps++;
                }
            }
           
            // break statement here
            // Good programming pratice discourage use of break statement
        }
       
        // End time
        this.endTime = System.currentTimeMillis();
    }
   
    public int [] getArray() {
        return this.array;
    }
}
Views: 4

Leave a Reply

Your email address will not be published. Required fields are marked *