In this tutorial, we will share a java program to sort the elements of an array using the bubble sort algorithm. Bubble sort algorithm is the simplest sorting algorithm.
In this program, we traversed the first element of the array to the last element. We compare the current element with the next element if the current element is greater than next element, then it swapped.
Copy the below Java program and execute it with the help Java Compiler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
public class BubbleSortExample { static void bubbleSort(int[] arr) { int n = arr.length; int temp = 0; for(int i=0; i < n; i++){ for(int j=1; j < (n-i); j++){ if(arr[j-1] > arr[j]){ //swap elements temp = arr[j-1]; arr[j-1] = arr[j]; arr[j] = temp; } } } } public static void main(String[] args) { int arr[] ={3,60,35,2,45,320,5}; System.out.println("Array Before Bubble Sort"); for(int i=0; i < arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(); bubbleSort(arr);//sorting array elements using bubble sort System.out.println("Array After Bubble Sort"); for(int i=0; i < arr.length; i++){ System.out.print(arr[i] + " "); } } } |
Array Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: Bubble Sort in Java with examples, Bubble Sort program in java, Java program, java program for bubble sort, java program to sort array, Java programs with examples, Java programs with output