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

Beginner Java Programming: The Bubble Sort Algorithm

Updated on September 12, 2013

Beginner Java Programming: The Bubble Sort Algorithm

One of the first things a student will learn when they begin their college programming curriculum are sorting algorithms. Every programmer must know these to be able to sort through data and be able to arrange that data into some kind of order either numerical or alphabetical. Most programming languages have these sorting algorithms already built in the language itself. However, most colleges will not introduce these built-in classes for beginner programming courses. This is due to the fact that most beginner programming classes want to teach the basic theories of programming algorithms and why the algorithms work.

Which leaves us to one of the most interesting and useful subjects for any programmer…the sorting algorithm. There are many out there in which students can use to sort data. Some are efficient while others are not so. With that in mind, I will now introduce you to the first sorting algorithm you will ever learn in programming….The Bubble Sort.

Java Rocks!!!!

Definition of the Bubble Sort:

The bubble sort is a sorting algorithm in which the programmer can pass different types of data to a function or class in which that data can be sorted in some kind of numerical or alphabetical order. Its main parts consist of an array variable, which holds in each record of a piece of data, and compares each record and places the values being compared in the correct order within the array variable. There is also a temporary variable involved for the comparison which help place the data within the correct record. Finally, all of these comparisons are done within two nested for/next loops which compare each value in every record within the array.

Now for the Code:

So, with the above said, here is some code to give you an example of a bubble sort algorithm using Java.

Bubble Sort Code in Java

//*****************************************************************
//Program: Example of a Bubble Sort in Java
//
// Version: 1.0
//
//*****************************************************************
package bubblesort;

/**
 *
 * @author Bink AKA 888 AKA BinkMeister AKA DUDE AKA Who knows ;)
 */

public class BubbleSort {

    //Create a bubblesort that takes a random array and sorts it ascending
    public static int [] bubblesortAsending(int [] inNumbers){
        
        int temp;//holds temp value
        
        //Loop through the whole array
        for(int i = 0; i < inNumbers.length; i++){
            //loop for comparing present value and stored value
            // if greater than, then values are swapped
            for (int j= 1; j < (inNumbers.length - i); j++ ){
                //swap the elemens if needed
                 if(inNumbers[j-1] > inNumbers[j]){
                     //store previous element data into temp variable
                    temp = inNumbers[j-1];
                    //Swap
                    inNumbers[j-1] = inNumbers[j];
                    //store new number into temp variable
                    inNumbers[j] = temp;
                    }
                               
            }
        }
        return inNumbers ;
    
}
    //creates a sorted array in which numbers are in descending order
    //The code is almost similar to the ascending funtion, except you use a less
    //than symbol (<) instead of a greater than (>) in the if statement
     public static int [] bubblesortDescending(int [] inNumbers){
        
        int temp;
        //loop through whole array
        for(int i = 0; i < inNumbers.length; i++){
            //loop for comparing present value and stored value
            // if less than, then values are swapped
            for (int j= 1; j < (inNumbers.length - i); j++ ){
                //swapped numbers.
                 if(inNumbers[j-1] < inNumbers[j]){
                    temp = inNumbers[j-1];
                    inNumbers[j-1] = inNumbers[j];
                    inNumbers[j] = temp;
                 }
                               
            }
        }
        return inNumbers ;
}
    public static void main(String[] args) {
        // create number array
        int [] numbers = {56,3,78,1000, 188, 77, 22,90};       
        //sort the array in asending order
        bubblesortAsending(numbers);
        // print out sorted array
         for(int i=0; i < numbers.length; i++){
            System.out.print(numbers[i] + " ");
            }
         //put a two line space into the output
         System.out.println();
         System.out.println();
         
         //sort array in descending order
         bubblesortDescending(numbers);
         //print out new array
         for(int i=0; i < numbers.length; i++){
            System.out.print(numbers[i] + " ");
         }
    }
}

After you run the above code you will see the following in your output window (if you are using NetBeans.)

Output Window After Program Program Runs in NetBeans

Description of the Code:

There are two major parts to the code above. First I define the Bubble Sort class within Java in which allows me to be able to sort any numerical data array. Within that Bubble Sort Class I created two functions. The first function will take in an integer array and will sort the array in ascending numerical order. The second one does the opposite; it actually will sort the array in descending order. So, basically, I created two functions that sort the array in similar fashion but do it in opposite order.

Now, I will explain how the Bubble sort really works using the first function “BubbleSortAscending.” First, the function declaration, public static int [] bubblesortAsending(int [] inNumbers), tells us that this function takes in an integer array from outside the class. So, this function will take in any integer array that is passed to it.

Next, we declare a temp variable. All this variable does is allow the for/next loop to store a piece of data temporarily that allows for swapping two pieces of data within the integer array. Basically, the temp variable holds a copy of a previous piece of data until the correct record where that data is to be stored is reached.

Next, we have the nested for/next loop that goes through every element in the array and compares them to see if the previous piece of data (or number in this case) is greater than the one after it and swaps the two. Here is the code for the nested for/next loop again:

Nested For/Next Loop

 //Loop through the whole array
        for(int i = 0; i < inNumbers.length; i++){
            //loop for comparing present value and stored value
            // if greater than, then values are swapped
            for (int j= 1; j < (inNumbers.length - i); j++ ){
                //swap the elemens if needed
                 if(inNumbers[j-1] > inNumbers[j]){
                     //store previous element data into temp variable
                    temp = inNumbers[j-1];
                    //Swap
                    inNumbers[j-1] = inNumbers[j];
                    //store new number into temp variable
                    inNumbers[j] = temp;
                    }
                               
            }

At first glance, the code seems to be a mess of “mass confusion,” which in a way it is. However, under strict observation, one can make out what it is trying to do. First, the initial for/next loop is just going through each element in the array. The next for/next loop is the one that allows the comparison between two numbers within each record. It actually is one step forward in the array than the initial loop in which this allows it to compare the next record within the array with the previous one. Again, in this case, it is making sure that the next element is not less than the previous. If it is, then the if/then statement allows it to store the value in that record into the temp variable and swap it with the number that was in the previous record. Finally, with the two records compared, the loop then goes to the next record and repeats the process using the temp variable to store any number that was deleted from the array. When all is done, you have a sorted array of integers which is returned from the class to your main program (i.e. “return inNumbers”).

On a final note, I told you there where two functions one for ascending and one for descending order. The descending function puts the array in descending order and is almost identical to the first function. However, the if/then statement uses a less than (<) symbol instead of a greater than (>) symbol. This is the only difference.

Finally you have the main function that allows you test the functions within the BubbleSort class.

Limitations to the Bubble Sort Algorithm:

On a final note, the Bubble Sort is great if you need to sort an array of data that is at most 100 – 10000 records. However, if you look at the algorithm, you can tell that it is not the very efficient algorithm and will start getting bogged down with more elaborate arrays. Indeed, it will not even hold up to even a two dimensional array. So, the Bubble Sort algorithm is only good for academic purposes unless you have a program in which only a small single dimensional array is necessary. So that is all I have to say about the Bubble Sort algorithm.

Cheers,

Bink

My Rating on JAVA NETBEANS

5 stars for JAVA NETBEANS IDE

Battle of the Java Compilers

Which of these two free compilers you think is the best.

See results

NETBEANS Java Compiler

NETBEANS is one of the best JAVA compilers any programmer could ever want. You can download the your own version at https://netbeans.org/. The compiler allows you be able to create an JAVA program with ease and the best thing about it...it is free. That is right free and you can have the power of JAVA within your finger tips.

Misc. Java Tutorial - The Bubblesort Algorithm: JLCreativeStudios

YouTube Video: Bubble Sort

Here is good bubble sort example for JLCreativeStudios that give another good example on how to create your own Bubble Sort Algorithm.

Poor C++

Tell me what you think.

    0 of 8192 characters used
    Post Comment

    No comments yet.

    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 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. (Privacy Policy)
    CloudflareThis is used to quickly and efficiently deliver files 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)
    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)
    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)
    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)
    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 YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (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 advertisements 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)