Programming the Bubble Sort Algorithm in Java

Beginner Java Programming: The Bubble Sort Algorithm

<p> </p> <p>One of the first algorithms taught in college programming classes are sorting algorithms. They are usually taught after the introduction of array variables. That is, first you learn how to create an array variable that can contain multiple records of the same type and shortly after you learn how you can sort them. </p> <p>There are three types of (academic) sorting algorithms and they are the Bubble sort, <a rel="NoFollow" href="https://www.sirgo.com/programming-an-insertion-sort-algorithm-in-java.aspx">Insertion Sort</a>, and the Merge sort. All three use some kind of loop or nested loop that loops through every record in an array and compares the data to see which one is greater or less than the other.</p> <p>The first sorting algorithm that you will usually learn is the bubble sort. The bubble sort is a sorting algorithm in which you compare every element in an array and sort them in the correct order. The bubble sort is good sort if you have arrays that do not contain many elements of data. That is, an array that only contains maybe a few hundred elements.</p> <p>In this article, I will cover how to program a bubble sort in Java though code. I will show first how to sort data in ascending order and then I will show you what you will need to change in the algorithm to sort the data in descending order.</p>


How Does the Bubble Sort Work?

 The function of the bubble sort algorithm is pretty basic.  It consists of two nested for loops that loop through each element of the array and one conditional if/then statement that compares the present element to a previous element.  If the previous element is less than (for a descending sort) or greater than (for an ascending sort), then the previous element is stored into a temp variable and the present element is put into the previous position or swapped.  This swapping of values is continued until the array has been completely transverse.  When all is done, you will have a completed sorted array. 

So, with that said, below is the code I used in Java to create two different bubble sort algorithms.  The first function sorts the array in ascending order and the second function sorts the array in descending order.

 

 

JAVA CODE:

 

 

  //*****************************************************************

//Program: Example of a Bubble Sort in Java

//

// Version: 1.0

package bubblesort;

/**

 *

 * @author Bink

 */

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 and new value

           // is stored in temp variable

            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

           // is stored in temp variable

            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] + ” “);

         }

    }

}

Explanation of the Code

I decided to put the two sorting functions in bold to give you a better look at the algorithms themselves.  You can pass any interger array to these functions and they will sort the array and pass it back to the main program.  Notice the nested for loops in each function.  To create the algorithm, you first have to create a for loop that will traverse every element within the array.  Then you have to create a nested loop that does the same but starts at the first element, not 0.  As the counter variable (i) increases (j) also increases in which each element is compared with the next through the if/then statement.  In the case of sorting in ascending order, if the value of the previous element (i.e. j-1) is greater, then the temp variable would store that value and the values are swapped.  This goes on until the whole array is sorted.  As for sorting in descending order, the process is almost identical with the exception that the if/then statement is looking for a less than value in j-1 instead of a greater than value.  Basically, to change from ascending to descending just change the > symbol to a < symbol within the if/then parameter parenthesis.

 

Conclusion:

 

 

So, now you know how to set up a bubble sort algorithm in Java.  This also works in other programming languages.  You just have to make sure the syntax of that particular language is followed. 

The bubble sort is a good algorithm if you need to sort a small array on the fly.  The reason I said a small array is the fact that the sort is very cumbersome and resource heavy due to the fact that you have to traverse every element of the array.  The best way in Java (in my opinion) for sorting arrays is to use Java’s built in Arrays class which has its own sorting function.  Indeed, using this class you can also sort String data and you would not have to worry too much on how many elements is in you array variables.    


Views All Time
Views All Time
169
Views Today
Views Today
1

Related Posts

Leave a Comment