bubble sort in java

problem

You wish to sort a list of numbers from the smallest to the greatest or vice versa. In this post we will see one of the sorting algorithms called Bubble Sort. Let’s suppose we have a list of 10 numbers, and wish to sort them in an ascending order.

SOLUTION

Using Bubble sort algorithm. This algorithm uses a greedy approach to the problem.

It loops the array of numbers and each time, it is getting two numbers (e.g. the number 10 and 3 below) and comparing them between them.

If the second number is smaller than the first one, it swaps them; putting the smaller first and the greater right after.

Repeating this process ends up sorting the array (in ascending order).

BubbleSort.java
				
					//the array with the unordered numbers
int[] numbers= new int[]{ 10,3,9,5,2,8,7,4,1,6};

//loop through the items
for (int i = 0; i <= numbers.length -1; i++) {
   for(int k= 0; k< numbers.length-i-1; k++){

       //take the first two numbers indices(k, k+1)
       if(numbers[k] > numbers[k+1]){ //compare them if they're in ascending order
           //swap them if not
           int temp = numbers[k];
           numbers[k] = numbers[k+1];
           numbers[k+1] = temp;
       }
   } //repeat
}
//print the sorted array
System.out.println(Arrays.toString(numbers));

				
			
running

Running it, let’s put it in a main method.

BubbleSort.java
				
					import java.util.Arrays;

public class BubbleSort {

   public static void main(String[] args) {
       //the array with the unordered numbers
       int[] numbers= new int[]{ 10,3,9,5,2,8,7,4,1,6};

       //loop through the items
       for (int i = 0; i <= numbers.length -1; i++) {
           for(int k= 0; k< numbers.length-i-1; k++){

               //take the first two numbers indices(k, k+1)
               if(numbers[k] > numbers[k+1]){ //compare them if they're in ascending order
                   //swap them if not
                   int temp = numbers[k];
                   numbers[k] = numbers[k+1];
                   numbers[k+1] = temp;
               }
           } //repeat
       }
       //print the sorted array
       System.out.println(Arrays.toString(numbers));
   }
}

				
			
output
Bubble Sort in java ascending order example

The numbers are now sorted in Ascending order from the lowest to the greatest.

Sorting in descending order

All we have to do is to change the condition when the pair of numbers are compared, as shown below:

BubbleSort.java
				
					if(numbers[k] < numbers[k+1]){ //compare them if they're in descending order

				
			

The full code:

BubbleSort.java
				
					import java.util.Arrays;

public class BubbleSort {

   public static void main(String[] args) {
       //the array with the unordered numbers
       int[] numbers= new int[]{ 10,3,9,5,2,8,7,4,1,6};

       //loop through the items
       for (int i = 0; i <= numbers.length -1; i++) {
           for(int k= 0; k< numbers.length-i-1; k++){

               //take the first two numbers indices(k, k+1)
               if(numbers[k] < numbers[k+1]){ //compare them if they're in descending order
                   //swap them if not
                   int temp = numbers[k];
                   numbers[k] = numbers[k+1];
                   numbers[k+1] = temp;
               }
           } //repeat
       }
       //print the sorted array
       System.out.println(Arrays.toString(numbers));
   }
}

				
			
output
Bubble Sort in java descending order example

conclusion

In this post, we saw how to use the Bubble Sort algorithm to sort a small array of numbers. This algorithm can easily be modified to sort numbers in ascending or descending just by changing the boolean expression in the if statement.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.