C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 set 1 ← n, p ← 1 Step 2 ➤ loop, Repeat through step 4 while (p ≤ n-1) set E ← 0 ➤ Initializing exchange variable. Step 3 ➤ comparison, loop. Repeat for i ← 1, 1, …... l-1. if (A [i] > A [i + 1]) then set A [i] ↔ A [i + 1] ➤ Exchanging values. Set E ← E + 1 Step 4 ➤ Finish, or reduce the size. if (E = 0) then exit else set l ← l - 1. 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 a0 < a1 so the array will remain as it is.
Now a1 > a2, so we will swap both of them.
As a2 < a3 so the array will remain as it is.
Here a3 > a4, so we will again swap both of them. Pass 2:
As a0 < a1 so the array will remain as it is.
Here a1 < a2, so the array will remain as it is.
In this case, a2 > a3, so both of them will get swapped. Pass 3:
As a0 < a1 so the array will remain as it is.
Now a1 > a2, so both of them will get swapped. Pass 4:
Here a0 > a1, 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 n-1 comparisons; in the second pass, it will do n-2; in the third pass, it will do n-3 and so on. Thus, the total number of comparisons can be found by; Therefore, the bubble sort algorithm encompasses a time complexity of O(n2) 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
|