Bubble sort in Java - Program to sort an Integer Array [Example] (original) (raw)

Bubble sort is one of the classic sorting algorithms,s which is used to explain sorting during various computer and engineering courses. Because of its algorithmic nature and simplicity, it's often used in various Java and C++ programming exercises. You may expect questions like the Write Java program to sort integer arrays using bubble sort during any programming interview. Since algorithmic questions are always tricky questions and not easy to code. Even the simplest of them can lead to confusion, especially if you are not gifted with a natural programming head. I have seen many developers fumble if asked to code on the spot. That's why it's advisable to do algorithmic and logical programming during training and learning programming and OOPS to get this skill of converting logic into code.

Let's come back to Bubble sort, In the Bubble sort algorithm we sort an unsorted array by starting from the first element and comparing it with the adjacent element. If the former is greater than later then we swap and by doing this we get the largest number at the end after the first iteration.

So in order to sort n elements you require n-1 iteration and almost n-1comparison. To recap here is the logic for the bubble sort sorting algorithm :

  1. Start comparing a[0] to a[1]

  2. If a[0] > a[1] then swap numbers e.g. a[0]=a[1] and a[1]=a[0]

  3. compare a[1] to a[2] and repeat till you compare last pair

  4. This is referred to as one pass and at the end of the first pass largest, the number is at last position and already sorted.

  5. Just repeat this comparison again starting from a[0] but this time going till second last pair only

How to sort integer array using bubble sort in Java

Here is a complete code example of a bubble sort in Java. It uses the same algorithm as explained in the first pass, it uses two loops. The inner loop is used to compare adjacent elements and the outer loop is used to perform Iteration. because of using two loops, it results in an order of n^2 which is not great in terms of performance.

If you are using Array List instead of the array then you can sort them using Collections.sort method for better performance, for details, check How to sort Array List in ascending and descending order.

Bubble sort is a good sorting algorithm to start with but you also need to learn more difficult and useful ones like QuickSort, MergeSort, HeapSort, as well as some advanced constant time, also known as O(n) sorting algorithms like Radix Sort, Bucket Sort, and Counting Sort if you want to do well on technical interviews.

If you are preparing for coding interviews then I suggest you double down into Algorithms as it takes time to develop the coding sense. I also recommend you check out Grokking the Coding Interview: Patterns for Coding Questions on Educative, an interactive portal for coding interviews to learn some useful patterns which can help you to solve many common coding problems.

Bubble sort in Java - program to sort integer array

Anyway, Now, let's see the Java program which implements this bubble sort logic to sort unsorted integer arrays.

package test;

import java.util.Arrays;

/**
* Java program to sort integer array using bubble sort sorting algorithm.
* bubble sort is one of the simplest sorting algorithm but performance
* of bubble sort is not good, it's average and worst-case performance
* ranges in O(n2) and that's why it is not used to sort a large set of
* unsorted data. Bubble sort can be used for educational and testing
* purpose to sort a small number of data to avoid the performance penalty.
* This program is also a good example of how to print contents of Array in Java

*
* @author http://java67.blogspot.com
*/
public classBubbleSort {

public static voidmain(String args[]) {
//testing our bubble sort method in Java
int[] unsorted = {32, 39,21, 45, 23, 3};
bubbleSort(unsorted);

//one more testing of our bubble sort code logic in Java
int[] test = { 5, 3, 2, 1};
bubbleSort(test);

}

/* * In bubble sort we need n-1 iteration to sort n elements * at end of first iteration larget number is sorted and subsequently numbers smaller * than that. */
public static voidbubbleSort(int[] unsorted){
System.out.println("unsorted array before sorting : " + Arrays.toString(unsorted));

// Outer loop - need n-1 iteration to sort n elements
for(int i=0; i<unsorted.length-1; i++){

//Inner loop to perform the comparison and swapping between adjacent numbers
//After each iteration one index from last is sorted
for(int j= 1; j<unsorted.length-i; j++){

//If the current number is greater than swap those two
if(unsorted[j-1] > unsorted[j]){
int temp = unsorted[j];
unsorted[j] = unsorted[j-1];
unsorted[j-1] = temp;
}
}
System.out.printf("unsorted array after %d pass %s: %n", i+1, Arrays.toString(unsorted));
}
}

}

Output:
unsorted array before sorting : [32, 39, 21, 45, 23, 3]
unsorted array after 1 pass [32, 21, 39, 23, 3, 45]:
unsorted array after 2 pass [21, 32, 23, 3, 39, 45]:
unsorted array after 3 pass [21, 23, 3, 32, 39, 45]:
unsorted array after 4 pass [21, 3, 23, 32, 39, 45]:
unsorted array after 5 pass [3, 21, 23, 32, 39, 45]:
unsorted array before sorting : [5, 3, 2, 1]
unsorted array after 1 pass [3, 2, 1, 5]:
unsorted array after 2 pass [2, 1, 3, 5]:
unsorted array after 3 pass [1, 2, 3, 5]

Java program for Bubble sort algorithm with exampleThat's all on How to sort integer array using Bubble sort in Java. We have seen a complete Java program for bubble sort and also printed output after each pass or iteration if you look carefully you will find that after each pass largest number gets sorted and the number of comparisons decreased.

As I said Bubble sort is not a high-performance sorting algorithm and you should by using Collection.sort() method from standard Java library to sort Collections or Arrays.sort() to sort Array in Java.

Also this the program demonstrates How to print contents of Array using Arrays.toString() as an array in Java doesn’t override toString and simply printing array using System.out.println(array) will only show default toString from java.lang.Object class instead of the contents of the array.

If you like this article and would like to try out a couple of more challenging programming exercises, then take a look at the following programming questions from various Interviews :

Thanks for reading this article so far. If you like this Bubble sort example in Java then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. Btw, what is your favorite sorting algorithm? Bubble Sort, Quick Sort, or Merge Sort?

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check this list of Free Data Structure and Algorithms Courses for Programmers.