Bubble Sort in Java

Bubble Sort is a generic algorithm to sort the elements and can be implemented in any programming language. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. it is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. This is repeated until the list gets exhausted, which indicates that the list is sorted.

Bubble Sort Example

Complexity

Worst Case Complexity O(n²)
Best Case Complexity O(n)
Average Case Complexity O(n²)
Worst case space complexity O(1) auxiliary

Here is an example coded in Java

package com.bharat.examples.collections;

public class BubbleSortExample
{
  public static void main(String[] args)
  {
    int unsortedArray[] = { 20, 55, 47, 0, -32, -99, 300, 7 };
    int i;

    doBubbleSort(unsortedArray);
    System.out.println("After sorting, the list elements are: ");
    for (i = 0; i < unsortedArray.length; i++)
    {
      System.out.print(unsortedArray[i] + " ");
    }
  }

  private static void doBubbleSort(int[] unsortedArray)
  {
    int temp;// to hold data while swapping
    int counter, index;
    int length = unsortedArray.length;

    // Loop once for each element in the array.
    for (counter = 0; counter < length - 1; counter++)
    {
      // Once for each element, minus the counter.
      for (index = 0; index < length - 1 - counter; index++)
      {
        // check if we need a swap or not.
        if (unsortedArray[index] > unsortedArray[index + 1])
        {
          // swap
          temp = unsortedArray[index];
          unsortedArray[index] = unsortedArray[index + 1];
          unsortedArray[index + 1] = temp;
        }
      }
    }
  }
}

Output

After sorting, the list elements are: 
-99 -32 0 7 20 47 55 300 
Advertisements

, , ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: