Loading...
I have memorised that bubble sort compares adjacent elements but I cannot picture why it sorts the whole list. Can someone explain how it works with a small example?
Bubble sort works by repeatedly comparing each pair of adjacent elements and swapping them if they are in the wrong order, so the largest value bubbles up to the end in each pass. Take the list 5, 1, 4, 2. First pass: compare 5 and 1, swap to get 1, 5, 4, 2; compare 5 and 4, swap to 1, 4, 5, 2; compare 5 and 2, swap to 1, 4, 2, 5. Now the largest, 5, is at the end. Second pass does the same on the rest, moving 4 into place, and so on. After each pass one more element is fixed in its final position. You repeat passes until no swaps are needed, which means the list is sorted. Its time complexity is O(n squared), so it is simple but slow for large lists.
Sign in as a tutor to answer this doubt.