ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Code Sample: Sort Numbers in Bubble Sort

Updated on October 31, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

Example of Bubble Sort in Java

Below is the java source code on sorting numbers using bubble sort . You can decide on how to sort a number either ascending or descending by just changing the comparison operator in the method BubbleSort.There are many sorting algorithms on sorting numbers but the most used is the selection sort. Actually, bubble sort is not a better choice on sorting numbers but it is pretty good to program while learning different sorting algorithms as well as recursion. It exposed the programmers on different ways on how to solve and program a certain problem and widen his/her knowledge as well as be able to compare its usefulness. After this program I will also upload the selection sort.

Updated:

Below is the quick link for the selection sort.

source:linux-mag.com
source:linux-mag.com

How Bubble Sort Works?

Bubble sort sorts numbers by comparing the number and its following number. For example we will sort the entered 6 numbers in ascending way and here is the user's input.

2 5 3 4 1 6

The first number is 2 and the following number is 5. Is 2 < 5? if yes, proceed. The second comparison will be 5 and 3. Is 5 < 3? since the answer is no, it will sort the numbers in this way.

2 3 5 4 1 6


Then, the next comparison is 5 and 4 and so on until it will be sorted properly from lowest to highest. Here is the complete list on how the numbers above sorted in bubble sort.

2 3 4 5 1 6

2 3 4 1 5 6

2 3 1 4 5 6

2 1 3 4 5 6

1 2 3 4 5 6 - end of sorting and this correct sorted numbers is what the program outputs to the screen



Below is the source code,

Java Source Code: How to sort numbers in Bubble Sort

//java class

public class BubbleSort
{

 public void bubbleSort(int[] arr){
     for(int i=0; i<arr.length; i++){
        for(int j=1; j<arr.length; j++){
            if(arr[j]< arr[j-1] ){
                int temp = arr[j];
                arr[j] = arr[j-1];
                arr[j-1] = temp;            
            }
        }
     }

     for(int i=0; i<arr.length; i++)
     {
         System.out.print(arr[i] + " ");
     }
}

}

//main class

import java.util.Scanner;

public class Main
{

   
    public static void main(String[] args)
    {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter the size of the array: ");
        int n = input.nextInt();
        int[] x = new int[n];

        System.out.print("Enter "+ n +" numbers: ");
        for(int i=0; i<n; i++)
        {
            x[i] = input.nextInt();
        }
        
        BubbleSort access = new  BubbleSort();
	System.out.print("The Sorted numbers: ");
        access.bubbleSort(x);
    }

}

Sample Output:

Enter the size of the array: 10

Enter 10 numbers: 100 35 45 3 7 2 1 500 200 15

The Sorted Numbers: 1 2 3 7 15 35 45 100 200 500

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      aloha 5 years ago

      How can this code be modified to include a System.out.print of the unsorted integers that have been entered ???

    • aisha91 profile image
      Author

      Rasna Aisha 5 years ago from Manila, Philippines

      Hello Aloha,

      Just add another for loop below the for loop on the Main.java.

      for(int k=0; k less than n; k++)

      {

      System.out.print(x[k] + " ");

      }

      That will output the unsorted entered integers. Just change the less than word into less than sign.

    • Island Tropical profile image

      Island Tropical 4 years ago

      very good.

    • aisha91 profile image
      Author

      Rasna Aisha 4 years ago from Manila, Philippines

      Thank you, just one of my random programming projects :)

    • profile image

      4 years ago

      I'm sorry I don't really understand the program listed here!

    • profile image

      vera 4 years ago

      i'm really interested in learning java program,but it seems not understandable to me because,this is my 3rd year learning it.So tell me what should i do?

    • profile image

      Anonymous 3 years ago

      this code has an error on line 27 saying "class, interface, or enum expected"

    • profile image

      sridatta 3 years ago

      public class BubbleSort {

      public static void main(String[] args)

      {

      int[] target={3,5,7,10,12,6,9,14,8};

      while(check(target)==true)

      {

      check(target);

      }

      for(int i=0;i less than target.length;i++)

      System.out.print(" "+target[i]);

      System.out.println(" ");

      }

      static public boolean check(int[] target){

      boolean result=false;

      int temp=0;

      for(int i=0;i less than target.length-1;i++)

      {

      if(target[i] greater than target[i+1])

      {

      temp=target[i];

      target[i]=target[i+1];

      target[i+1]=temp;

      result=true;

      }

      }

      return result;

      }

      }

    • profile image

      sridatta 3 years ago

      the above code much efficient as it iterates only if there is a swap between the number instead of iterating n*n times !!!

    • profile image

      dhanashri 3 years ago

      can u pls help me to display all passes of bubble sort in given program

    • profile image

      java2novice 3 years ago

      nice, for more java examples, visit http://java2novice.com site

    • profile image

      Sangita 2 years ago

      Its good. Ok I am trying to built a site for java programming..

      I have just started it : www.java-programming-tutorial.com/2014/07/java-programming-tutorial.html

    • profile image

      2 years ago

      good more

    Click to Rate This Article