# Java Bubble Sort Implementation

**Bubble sort is by using a flag in a while loop to determine if the given list is sorted or not.** Each loop will bubble up the largest value(smallest value for descending order) of the remaining unsorted elements to the correct position. Bubble up means the swap of two values, when looping through each element in the list, if the value of the current position is larger than the value of the next position, swap them and set the swapped flag to true, so that the next outer while loop will loop through list again to do the next round of bubbling. Each inner loop will bubble up one value to the correct position, thus the number of inner loops will decrease by 1 in the next iteration.

Here is an example of bubble sort in Java

public class BubbleSort { public static void bubbleSort(int[] num) { boolean swapped=true; int n=num.length; int temp=0; int count=0;//counter to counter the number of loops, for illustration purpose only not needed for the sorting itself. //the list is sorted if the last loop didn't do any swaps while(swapped) { swapped=false; //looping through the list and swap the current position and the next position as needed for(int i=0; i<n-1; i++) { //swap if the value of the current position is larger than the value of the next position //change > to < for descending order if(num[i]>num[i+1]) { temp=num[i]; num[i]=num[i+1]; num[i+1]=temp; swapped=true; } //for illustration purpose only not needed for the sorting itself. System.out.print(count+" During Sorting: "); printArr(num); count++; } //After one whole iteration of the inner for loop, the last element should be in the correct position, thus we don't look at again in the next iteration. //Hence we decrease n by 1, so the number of inner for loop will decrease by 1 in the next iteration. n--; } System.out.println("count>>"+count); } public static void printArr(int[] arr) { for(int i=0; i<arr.length; i++) { System.out.print(arr[i]+" "); } System.out.println(); } public static void main(String args[]) { int [] intArr={56,1,64,3,22}; System.out.print("Before: "); printArr(intArr); bubbleSort(intArr); System.out.print("After: "); printArr(intArr); } }

Output of the above bubble sort

Before: 56 1 64 3 22 0 During Sorting: 1 56 64 3 22 1 During Sorting: 1 56 64 3 22 2 During Sorting: 1 56 3 64 22 3 During Sorting: 1 56 3 22 64 4 During Sorting: 1 56 3 22 64 5 During Sorting: 1 3 56 22 64 6 During Sorting: 1 3 22 56 64 7 During Sorting: 1 3 22 56 64 8 During Sorting: 1 3 22 56 64 count>>9 After: 1 3 22 56 64

See Insertion Sort, Merge Sort and other Sortings

**Search within Codexpedia**

**Search the entire web**