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.
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] + " "); } } }
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
).
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
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 TAGS
View all Courses