Back to DSA Course
DSA Course
It compares the adjacent elements and swaps until the sorting is achieved.
For example,
int[] num= {90,24,46,35,32};
Lets see how bubble sort works
First round: 90,24,46,35,32 24,90,46,35,32 24,46,90,35,32 24,46,35,90,32 24,46,35,32,90 Second round: 24,46,35,32,90 24,35,46,32,90 24,35,32,46,90 Third round: 24,35,32,46,90 24,32,35,46,90
That's it after 3 rounds of adjacent element comparison we have achieved the sorted order using Bubble sort.
Let's start coding for bubble sort,
package com.praveen.sort; import java.util.Arrays; public class BubbleSort { public static void main(String[] args) { int[] arr = { 90, 24, 46, 35, 32 }; bubble(arr); System.out.println(Arrays.toString(arr)); } private static void bubble(int[] arr) { boolean swapped; // run the steps n-1 times for (int i = 0; i < arr.length; i++) { swapped = false; // for each step, max item will come at the last respective index for (int j = 1; j < arr.length - i; j++) { // swap if the item is smaller than the previous item if (arr[j] < arr[j - 1]) { // swap int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; swapped = true; } } // if you did not swap for a particular value of i, it means the array is sorted // hence stop the program if (!swapped) { // !false = true break; } } } }
Output
[24, 32, 35, 46, 90]