Advertisements
Advertisements
Question
Define the procedure of bubble sort with an example.
Definition
Advertisements
Solution
Bubble sort is a comparison-based algorithm that sorts an array by repeatedly swapping adjacent elements if they are in the wrong order. In each complete pass through the array, the largest unsorted element "bubbles up" to its correct position at the end. This process repeats for the remaining unsorted elements until the entire array is arranged in order.
Example:
Unsorted Array: [5, 1, 4, 2]
- Pass 1:
- Compare 5 and 1 → Swap → [1, 5, 4, 2]
- Compare 5 and 4 → Swap → [1, 4, 5, 2]
- Compare 5 and 2 → Swap → [1, 4, 2, 5]
- Pass 2:
- Compare 1 and 4 → No swap → [1, 4, 2, 5]
- Compare 4 and 2 → Swap → [1, 2, 4, 5]
- Pass 3:
- Compare 1 and 2 → No swap → Final Sorted Array:
shaalaa.com
Is there an error in this question or solution?
Chapter 8: Arrays - Sort & Search - Exercises [Page 197]
