Bubble Releases in Java - Sort an Array of Integers
The bubble sort algorithm is one of the classic algorithms that is used to explain sorting during university classes. It is also used in C or C++ exercises thanks to its simplicity. You often hear about how to write a program that sorts an array using the Bubble sort algorithm to sort an array of integers in ascending or descending order.
In the Bubble sort algorithm, sorting an unordered array starts with the first element and compares it with the adjacent element and if it is larger, they are exchanged. By doing this, we get the largest number at the end after the first iteration. So for n elements, you need n-1 iterations and n-1 comparisons to the maximum and is performed in a complexity that is equal to O(n²). which makes it less usable when sorting on a table that contains a very large number of elements. In this case, it becomes the slowest and heaviest sorting algorithm, which ranks it among the bad sorting algorithms. Let's take a step-by-step look in this example to sort an array using bubble sorting, as we said after each step the largest number is sorted.
References:
Java program to bubble sort
Bubble Sort Algorithm in Java with Example
In the Bubble sort algorithm, sorting an unordered array starts with the first element and compares it with the adjacent element and if it is larger, they are exchanged. By doing this, we get the largest number at the end after the first iteration. So for n elements, you need n-1 iterations and n-1 comparisons to the maximum and is performed in a complexity that is equal to O(n²). which makes it less usable when sorting on a table that contains a very large number of elements. In this case, it becomes the slowest and heaviest sorting algorithm, which ranks it among the bad sorting algorithms. Let's take a step-by-step look in this example to sort an array using bubble sorting, as we said after each step the largest number is sorted.
Bubble sort implementation in Java
Here is a Java program that implements the bubble sort algorithm.public class tri_a_bulles_array{Let's see what this program looks like:
public static void main(String[] args) {
int T[] = {99, 45, 68, 18, 34, 26, 50, 8, 55, 10};
System.out.print("Before sorting ");
for (int n:T)
System.out.print(n+" ");
T = tri_a_bulles(T);
System.out.print("\nAfter sorting ");
for (int n:T)
System.out.print(n+" ");
}
static int[] tri_a_bulles(int T[])
{
int temp;
for(int i = T.length-1 ; i>=1 ; i--)
{
for(int j = 0 ; j< i ; j++)
if(T[j] > T[d+1])
{
temp = T[d+1];
T[j+1]=T[j];
T[j]=temp;
}
}
return T;
}
}
Before sorting 99 45 68 18 34 26 50 8 55 10You can go further to see sorting methods Java predefined java.util.Arrays which are Arrays.sort() and Collections.sort().
After sorting 8 10 18 26 34 45 50 55 68 99
References:
Java program to bubble sort
Bubble Sort Algorithm in Java with Example