# What is a Bubble sort in Java

sorting
iterative sort
bubble
simple sort
java

Bubble sort is a simple sorting algorithm that compares adjacent elements of an array and swaps them if the element on the right is smaller than the one on the left.

It is an in-place sorting algorithm i.e. no extra space is needed for this sort, the array itself is modified.

## Visualizing the sorting

This is the array to be sorted

1 of 23

## Implementation

Now that you have seen how Bubble sort works, let’s code the bubble sort algorithm for the above-given example.

Change the values of arr to see how it works on different arrays.

class sorting {

public static void bubbleSort(int [] sort_arr, int len){

for (int i=0;i<len-1;++i){

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

if(sort_arr[j+1]<sort_arr[j]){

int swap = sort_arr[j];
sort_arr[j] = sort_arr[j+1];
sort_arr[j+1] = swap;

}
}
}
}

public static void main( String args[] ) {
int [] array = {10,5,3,1,24,12};
int len = array.length;
bubbleSort(array,len);

for(int i = 0; i<len; ++i){
System.out.print(array[i] + " ");
}
}
}

## Understanding implementation

• The first step is to create a method, bubbleSort, that takes the array as the input to be sorted, sort_arr, and the length of the array, len, as seen on line 3 in the code above.

• The second step is to create an outer for loop which will iterate over each element of the array as shown on line 5.

• The third step is to create an inner for loop as shown on line 7. This for loop starts from the first element of the array till the second last index, (len - i - 1).

• Each time one index less than the last is traversed as at the end of each iteration, the largest element for that iteration reaches the end.
• Within the nested for loop is the if condition from lines 9 to 15. This checks that if the element on the left is greater than that on the right. If so, it swaps the two elements.

Note: The outer loop will iterate over all elements in the array even if the array is already completely sorted

## Time Complexity

Since there are two nested loops within the algorithm, the time complexity will be O(n^2) where n is equivalent to the length of the array to be sorted.

RELATED COURSES
Related Courses
Related Courses