Home Java Beginners Arrayexamples Bubble Sorting in Java


Share on Google+Share on Google+

Bubble Sorting in Java

In this example we are going to sort integer values of an array using bubble sort.

Bubble Sorting in Java



In this example we are going to sort integer values of an array using bubble sort.

Bubble sort is also known as exchange sort. Bubble sort is a simplest sorting algorithm. In bubble sort algorithm array is traversed from 0 to the length-1 index of the array and compared one element to the next element and swap values in between if the next element is less than the previous element. In other words, bubble sorting algorithm compare two values and put the largest value at largest index. The algorithm follow the same steps repeatedly until the values of array is sorted. In worst-case the complexity of bubble sort is O(n2) and in  best-case the complexity of bubble sort is Ω(n).
Code description:

Bubble Sorting is an algorithm in which we are comparing first two values and put the larger one at higher index. Then we take next two values compare these values and place larger value at higher index. This process do iteratively until the largest value is not reached at last index. Then start again  from zero index up to n-1 index. The algorithm follows the same steps iteratively unlit elements are not sorted. 


Working of bubble sort algorithm:

Say we have an array unsorted  A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by bubble sort algorithm to sort the values of an array.
 1.Compare A[0] and A[1] . 
 2.If A[0]>A[1] then Swap A[0] and A[1].
 3.Take next A[1] and A[2].
 4.Comapre these values.
If A[1]>A[2]  then swap A[1] and A[2]
at last compare A[n-1] and A[n]. If A[n-1]>A[n] then swap A[n-1] and A[n]. As we see the highest value is reached at nth position. At next iteration leave nth value. Then apply the same steps repeatedly on A[0],A[1],A[2]................ A[n-1] elements repeatedly until the values of array is sorted.

In our example we are taking the following array values
12 9 4 99 120 1 3 10

The basic steps followed by algorithm:-
In the first step compare first two values 12 and 9.
12 9 4 99 120 1 3 10

As 12>9 then we have to swap these values 
Then the new sequence will be 
9 12 4 99 120 1 3 10

In next step take next  two values 12 and 4 
9 12 4 99 120 1 3 10

Compare these two values .As 12>4 then we have to swap these values. 
Then the new sequence will be
9 4 12 99 120 1 3 10

We have to follow similar steps up to end of array. e.g.
9 4 12 99 120 1 3 10
9 4 12 99 120 1 3 10
9 4 12 99 1 120 3 10 
9 4 12 99 1 120 3 10
9 4 12 99 1 3 120 10
9 4 12 99 1 3 10 120

When we  reached at last index .Then restart same steps unlit the data is not sorted.

The output of this example will be :
1 3 4 9 10 12 99 120 

The code of the program :

public class bubbleSort{
  public static void main(String a[]){
  int i;
  int array[] {12,9,4,99,120,1,3,10};
  System.out.println("Values Before the sort:\n");
  for(i = 0; i < array.length; i++)
  System.out.printarray[i]+"  ");
  bubble_srt(array, array.length);
  System.out.print("Values after the sort:\n");
  for(i = 0; i <array.length; i++)
  System.out.print(array[i]+"  ");

  public static void bubble_srtint a[]int ){
  int i, j,t=0;
  for(i = 0; i < n; i++){
  for(j = 1; j < (n-i); j++){
  if(a[j-1> a[j]){
  t = a[j-1];

Output of the example:

C:\array\sorting>javac bubbleSort.java
C:\array\sorting>java bubbleSort
Values Before the sort:
12  9  4  99  120  1  3  10
Values after the sort:
1  3  4  9  10  12  99  120

Download this example.


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 28, 2007

Related Tutorials

Ask Questions?    Discuss: Bubble Sorting in Java   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
April 2, 2011
comment about program

it's nice for sharing knowledge about programs
April 9, 2011

what is the purpose of the inner for loop?
April 19, 2011
Wrong statement

for(j = 1; j < (n-i); j++) this will not sort last element. for(j = 1; j < n; j++) This will fix issue. Enjoy!!
August 20, 2011

nice explanation
Mike Partyka
September 13, 2011
Bug in the bubble sort

The for loops are a little off: for(i = 0; i < n; i++){ for(j = 1; j < (n-i); j++){ should be: for(i = 0; i < (n-1); i++){ for(j = 1; j < n; j++){
November 10, 2011
Array sorting without any sorting techniques

//sorting based on ascending and descending order based on asc or dsc passed in command prompt.... public class Sort2 { public static void main(String[] args) { //String order = args[0]; int[] a = stringToInt(args); int arrayLength=a.length; for(int i=0; i<arrayLength-1; i++) { if(args[0].equalsIgnoreCase("asc")) { int asc=returnMinIndex(a,i); a=swap(a, i, asc); } else if(args[0].equalsIgnoreCase("dsc")) { int dsc=returnMaxIndex(a,i); a=swap(a, i, dsc); } // for(int j = 0; j <a.length; j++) to see the sorted array // System.out.print(a[j]+" "); } for(int j = 0; j <a.length; j++) System.out.print(a[j]+" "); } //method to return Maximum Index Value public static int returnMaxIndex(int[] a, int startIndex) { System.out.println("startIndex is " +startIndex); int maxValue = a[startIndex]; int maxIndex = startIndex; for (int i = startIndex+1; i < a.length; i++) { if (a[i] > maxValue) { maxValue = a[i]; maxIndex = i; } } System.out.println("maxIndex=" +maxIndex); return maxIndex; } //method to return minimum Index value public static int returnMinIndex(int[] a, int startIndex) { System.out.println("startIndex is " +startIndex); int minValue = a[startIndex]; int minIndex = startIndex; for (int i = startIndex+1; i < a.length; i++) { if (a[i] < minValue) { minValue = a[i]; minIndex = i; } } System.out.println("minIndex=" +minIndex); return minIndex; } //method to swap to elements public static int[] swap(int a[],int minIndex , int maxIndex ) { int t=0; t= a[minIndex]; a[minIndex]=a[maxIndex]; a[maxIndex]=t; return a; } //method to convert string array to int array public static int[] stringToInt(String[] args) { int arr[]= new int[args.length-1]; for(int i= 0; i<args.length-1; i++) { arr[i] = Integer.parseInt(args[i+1]); //args[i+1]--- to ignore asc or dsc } return arr; } }
Niladri Dutta
November 24, 2011
About the program

Excellent thank you so much you helped me so much i cant xpress it in words...........!!!!!!!!!!!
Sidharth Sahoo
February 19, 2012

Thanks a lot.. I am a student of Class XI of ISC Course.. I had forgotten the syntax of bubble sorting.. We did it in Class X but I had lost my notes... Your website was of great help to me before my exams...
March 8, 2012
Proper code for bubble sort

The algoritthm presented here is not a bubble sort. The proper code (swap just swaps two elements in array) should be: private static void bubbleSort(int array[]){ int swaps = 0; do{ swaps = 0; for(int i = 1; i < array.length; i++){ if( array[i] < array[i-1]){ swaps++; swap(array, i, i-1); } } }while( swaps != 0 ); }
April 27, 2012
Bubble Sort

How can I modify your code so that we can have different input sizes such as 10,000, and 10,000,000, and then output the time that they finish running bubble sort using various input sizes?
March 25, 2012
program using buffered reader

how do i write the same program using buffered reader?
June 6, 2012

very nice
June 17, 2012

get lost
rajesh yadav
August 15, 2012
To get Job as Java Developer

i am begainer of software industries(sply in java ) my programing skills is not so good so how we improve my skills?to survive in software industries????.I am 2010 passout B.Tech (ECE)student.
August 16, 2012
sorting programme

the given sorting programme is really easy.thanks
September 18, 2012
to improve bubbulesort Example

you r change the value from two place like insertion sort so there is change small part of code. public static void bubble_srt( int a[], int n ){ int i, j,t=0; for(i = 0; i < n; i++){ for(j = 1; j < (n-i); j++){ if(a[j-1] > a[j]){ a[j]=a[j]+a[j-1]; a[j-1]=a[j]-a[j-1]; a[j]=a[j]-a[j-1]; }
December 13, 2012

what is the best technique in programming?
nilo botay
September 30, 2012
cs125(descrete math)

your code is very good you know?i almost understand it but i do not..paglung-ag sa sa sunod para dili ta manga pasmo huh??
pooja nakil
October 18, 2012
core java

easy to understand nice...............
December 30, 2012
Bubble sort

WHy can't we do bubble sort with only one for loop ??
December 4, 2012

Bryan Hayag
June 20, 2013
My Version of Bubble Sort

//You can try this Code if this fits your needs... import java.io.*; import java.util.*; public class BubbleSort { public static void main(String args[]) throws IOException { int i; Scanner in = new Scanner(System.in); System.out.println("Please enter number of items to Sort:"); int nItems = in.nextInt(); int[] ax = new int[nItems]; for (i=0;i<nItems;i++) { System.out.print("\nEnter a Number:"); ax[i]=in.nextInt(); } bubble_srt(ax, ax.length); System.out.print("\nThe values after sort: \n"); for (i=0; i< ax.length; i++) { System.out.print(ax[i]+" "); } System.out.println(); System.out.println("\nPAUSE..."); } public static void bubble_srt(int a[], int n) { int i,j,t=0; for (i=0; i<n; i++) { for (j=1; j<(n-i); j++) { if (a[j-1] > a[j]) { t=a[j-1]; a[j-1]=a[j]; a[j]=t; } } } } }
aki claks
June 30, 2013
data structure

thanks for the codes, it helps a lot but how can i convert it into (GUI)Graphical User Interface?
JV a'k'a ( Lee Min Ho )
March 19, 2014

All i can say about the program is AWESOME ! :)
Niladri Dutta
November 24, 2011
Wrong statement

Objection avi the actual statement is for(j=0;j<n-i-1;j++)