Simple Sorting Algorithms: Bubble Sort Seletion Sort Insertion Sort
Simple Sorting Algorithms: Bubble Sort Seletion Sort Insertion Sort
BUBBLE SORT
Compare each element (except the last one) with its neighbor to the right
If they are out of order, swap them This puts the largest element at the very end The last element is now in the correct and final place
Compare each element (except the last two ) with its neighbor to the right
If they are out of order, swap them This puts the second largest element next to last The last two elements are now in their correct and final places
Compare each element (except the last three ) with its neighbor to the right
Continue as above until you have no unsorted elements on the left
2
7 2 8 5 4
2 7 5 4 8
2 5 4 7 8
2 4 5 7 8
2 7 8 5 4
2 7 8 5 4 2 7 5 8 4 2 7 5 4 8
2 7 5 4 8
2 5 7 4 8 2 5 4 7 8
2 5 4 7 8
2 4 5 7 8
2 4 5 7 8
(done)
The Selection Sort might swap an array element with itself --this is harmless, and not worth checking for
2 4 8 5 7 2 4 5 8 7
The outer loop executes n-1 times The inner loop executes about n/2 times on average (from n to 2 times) Work done in the inner loop is constant (swap two array elements)
2 4 5 7 8
7
3 4 7 12 14 14 20 21 33 38 10 55 9 23 28 16
less than 10
12 14 20 21 38 3 4 7 10 12 14 14 21 20 33 33 10 38 55 9 23 28 16 sorted