DAA Bubble SortBubble Sort, also known as Exchange Sort, is a simple sorting algorithm. It works by repeatedly stepping throughout the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is duplicated until no swaps are desired, which means the list is sorted. This is the easiest method among all sorting algorithms. AlgorithmStep 1 ➤ Initialization Step 2 ➤ loop, Step 3 ➤ comparison, loop. Step 4 ➤ Finish, or reduce the size. How Bubble Sort Works
For each iteration, the bubble sort will compare up to the last unsorted element. Once all the elements get sorted in the ascending order, the algorithm will get terminated. Consider the following example of an unsorted array that we will sort with the help of the Bubble Sort algorithm. Initially, Pass 1:
As a_{0} < a_{1} so the array will remain as it is.
Now a_{1} > a_{2}, so we will swap both of them.
As a_{2} < a_{3} so the array will remain as it is.
Here a_{3} > a_{4}, so we will again swap both of them. Pass 2:
As a_{0} < a_{1} so the array will remain as it is.
Here a_{1} < a_{2}, so the array will remain as it is.
In this case, a_{2} > a_{3}, so both of them will get swapped. Pass 3:
As a_{0} < a_{1} so the array will remain as it is.
Now a_{1} > a_{2, }so both of them will get swapped. Pass 4:
Here a_{0} > a_{1}, so we will swap both of them. Hence the array is sorted as no more swapping is required. Complexity Analysis of Bubble SortInput: Given n input elements. Output: Number of steps incurred to sort a list. Logic: If we are given n elements, then in the first pass, it will do n1 comparisons; in the second pass, it will do n2; in the third pass, it will do n3 and so on. Thus, the total number of comparisons can be found by; Therefore, the bubble sort algorithm encompasses a time complexity of O(n^{2}) and a space complexity of O(1) because it necessitates some extra memory space for temp variable for swapping. Time Complexities:
Advantages of Bubble Sort
Disadvantages of Bubble Sort
Next TopicSelection Sort
