ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

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

      3 years ago

      good more

    • profile image

      Sangita 3 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

      java2novice 4 years ago

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

    • profile image

      dhanashri 4 years ago

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

    • profile image

      sridatta 4 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

      sridatta 4 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

      Anonymous 4 years ago

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

    • profile image

      vera 5 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

      5 years ago

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

    • aisha91 profile image
      Author

      Rasna Aisha 5 years ago from Manila, Philippines

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

    • Island Tropical profile image

      Island Tropical 5 years ago

      very good.

    • aisha91 profile image
      Author

      Rasna Aisha 6 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.

    • profile image

      aloha 6 years ago

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

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)