Title: Bubble Sort
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Bubble Sort

In this video, another sort algorithm will be developed from scratch. Some discussion about Sort timings is done at the end.

The Solution that is developed in this video is as follows:


import java.util.Scanner;


public class BubbleSort {

    static void sort(int[] arr)
    {
        for (int i=0; i < arr.length; i++)
        {
            if ( !bubbleLargest(arr, arr.length-i))
                break;
        }
    }

    static boolean bubbleLargest(int[] arr, int len)
    {
        boolean somethingWasSwapped = false;

        for (int i=0; i < len -1; i++)
        {
            if (arr[i] > arr[i+1])
            {
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
                somethingWasSwapped= true;
            }
        }
        return somethingWasSwapped;
    }

    public static void main(String[] args) {
        System.out.println("What is the number to sort: ");
        Scanner keyboard = new Scanner(System.in);
        int n = keyboard.nextInt();

        int[] arr = new int[n];
        for (int i=0; i < n; i++)
        {
            arr[i] = (int)(1 + 10000*Math.random());
        }

        long time1 = System.currentTimeMillis();
        sort(arr);
        long time2 = System.currentTimeMillis();
        double seconds = (time2 - time1)/ 1000.0;

        System.out.println("It took "+ seconds + " Seconds");

    }

}


Last Modified: September 30, 2013 4:27 AM