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 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.


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++)



For more Algorithms and Java Programing Test questions and sample code follow below links


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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s