Sorting Problem
Sort an array of numbers in order
[5, 6, 3, 2, 1]
[1, 2, 3, 5, 6]
Bubble Sort
Bubble Sort is an algorithm which always examines adjacent elements, swapping those which are "out of order"
Bubble Sort
We start at index 0 and compare the item to the right:
[5, 6, 3, 2, 1]
This time, the two elements are already ordered properly
Bubble Sort
So we slide the window one to the right
[5, 6, 3, 2, 1]
Comparing reveals we have to swap!
Bubble Sort
[5, 3, 6, 2, 1]
We swapped the 3 and 6. Then, we continue to slide the comparison window to the right.
Bubble Sort
Following this process will *always* result in the highest element being "bubbled" to the top.
[5, 3, 6, 2, 1]
[5, 3, 2, 6, 1]
[5, 3, 2, 1, 6]
Now - the top element is in it's place. We just repeat the process for the items to the left of 6.
Bubble Sort
Bubble Sort is an algorithm which always examines adjacent elements, swapping those which are "out of order"
What is the worst case scenario for this algorithm?
How many comparisons per iteration? How many swaps?
How many maximum iterations?
Bubble Sort
Big O
Bubble Sort
Big O
What is the worst case scenario for this algorithm?
When the list is in reverse order.
How many comparisons per iteration? How many swaps?
The first iteration has n. Second has n-1. Third has n-2 ... and so on. Swaps are the same, but you may to fewer swaps in better cases.
How many maximum iterations?
n
Bubble Sort
Big O
So Bubble Sort is
O(n^2)
Questions?
Bubble Sort
By Wenbin He
Bubble Sort
- 598