Bubble Sort is used to sort the given set of n elements which are provided to us in the form of an array. In bubble sort, elements are compared from the beginning and are sorted based on their values. Suppose if we have to sort an array in the ascending order, the bubble sort will compare the first two elements of the array, if the first one is greater than the second, it swaps their positions. A similar thing is done until the last element of the array.
Let's learn the working of Bubble sort step-by-step
We will take an unsorted array given below to explain the working:
In Bubble sort, we first check the first two elements of the array. The one which is smaller is kept first. In this case, out of 13 and 32, 13 is smaller so its already sorted.
We will take the next two elements in the array. Out of 32 and 26, 26 is smaller, so we put 26 before 32. The sorted array will be:
In a similar manner, we will now compare 32 and 34, out of these two, 32 is smaller so the array is sorted. Now take the next two 34 and 9.
As 9 is smaller than 34, interchange their positions. the array will now become:
Now, as you can see, 9 is not in the sorted position, this element of the array will be checked for each preceding element. each iteration will sort the array till its completely sorted.
We will look into this whole iteration process through an Algorithm. We assume that list is an array with n no. of elements and swap function swaps the elements to sort the array.
begin BubbleSort (list)
for all elements of list
if list[i] > list [i+1]
swap (list[i], list[i+1])