Back to community
Computer ScienceClass 12

How does the bubble sort algorithm actually work step by step?

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?

Asked by Sneha Iyer 8 45d ago
Need a Computer Science tutor? Browse verified Computer Science tutors near you.

1 answer

3

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.

S
Sanjay Pillai
355 pts· 45d ago

Sign in as a tutor to answer this doubt.