Bubble Sort/ Sinking Sort Java Program


Bubble Sort also called Sinking Sort is a comparison sort algorithm where smaller or larger “bubble” elements move to top.

Complexity

Complexity of bubble sort is O(n2) in both average and worst case while O(n) in best case when elements are already sorted. Where n is number of elements.

Drawback

It will not be efficient in the case of a reverse-ordered collection or number of elements are high.

import java.util.Scanner;

public class BubbleSort {
	public static void main(String []args) {
	    int n, c, d, swap;
	    //For User Input
	    Scanner in = new Scanner(System.in);

	    System.out.println("Input number of integers to sort");
	    n = in.nextInt();

	    int array[] = new int[n];

	    System.out.println("Enter " + n + " integers");

	    for (c = 0; c < n; c++)
	      array[c] = in.nextInt();

	    for (c = 0; c < ( n - 1 ); c++) {
	      for (d = 0; d < n - c - 1; d++) {
/* In case of descending order use < */
if (array[d] > array[d+1]) 
	        {
	          swap       = array[d];
	          array[d]   = array[d+1];
	          array[d+1] = swap;
	        }
	      }
	    }
	    System.out.println("Sorted list of numbers");

	    for (c = 0; c < n; c++)
	      System.out.println(array[c]);
	  }
	}

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Algorithm, Complexity, Java, Sort and tagged , , , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

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