Bubble Sort Program in Java Language

Bubble sort is the simplest sorting algorithm that is used in the java language. The main objective of this sorting is a comparison-based algorithm; it compares the pair of any adjacent elements with those elements that are swapped in case if they are not in order. Bubble sort in java is not suitable for any type of large dataset because the average and worst-case complexity of it is Ο(n2), in which n is the number of items.

To see more about Bubble sort, we discuss further what is bubble sort example in java in this discussion. Through bubble sort, users can create a java program to sort the array elements. It forms one of the simplest algorithms understandable by human beings.

Bubble Sort Program in Java

Now we share bubble sort code in java that is printing and displaying an output so that you can understand better about the bubble sort by reading the program for bubble sort in java. In this algorithm, an array is traversed from the very first element to the last element. It is comparing every element with the next element. In case the current element is greater than the next element, it changes or swaps its position.

Example:

We can see Bubble Sort Example in Java code here

public class BubbleSort {

static void bubbleSort(int[] arr) {

int n = arr.distance;

int temp = 0;

for(int i = 0; i < n; i++) {

for(int j=1; j < (n-i); j++) {

if(arr[j-1] > arr[j]) {

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

}

}

}

}

public static void main(String[] args) {

int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

System.out.println("Array for Bubble Sort");

for(int i = 0; i < arr.distance; i++) {

System.out.print(arr[i] + " ");

}

System.out.println();

bubbleSort(arr);

System.out.println("Array at the end of Bubble Sort");

for(int i = 0; i < arr.distance; i++) {

System.out.print(arr[i] + " ");

}

}

}

Output

Array for Bubble Sort

2 5 -2 6 -3 8 0 -7 -9 4

Array at the end of Bubble Sort

-9 -7 -3 -2 0 2 4 5 6 8

Also Read: Palindrome Program in Java

Conclusion

This was a discussion on bubble sort in java, and we saw how to write programs and codes for bubble sort in java with examples. For more details, leave a reply in the box given below.

FAQ’s

How does Bubble Sort work?

In bubble sorting, we just have to take O(n2) and keep the algorithm short and precise so easily swap the numbers on their value. We take any unsorted array to start with its very first two elements, to check which one is greater by comparison.

Which is the easiest sorting algorithm?

Bubble sort is the simplest one of all the sorting algorithms. It works by going through the entire array and forms a comparison between them both to check which is greater and which one is smaller. It swaps those numbers to form a list in ascending order.