Sorting Algorithms Ellysa N. Kosinaya
Overview Icebreaker KLA: The “Human Sorting” Summary of the 4 sorting algorithms
icebreaker Need 6-8 volunteers Birthday sort Height sorting
Kla: Human sorting Divide up to 4 groups Each group perform a specific sorting algorithm (e.g. bubble, selection, merge, quick) similar to icebreaker. Discuss the time complexities (i.e. best, worst, average)
summary Selection Sort Bubble Sort Merge Sort (Divide-and-Conquer method) Quick Sort (Divide-and-Conquer method)
Selection Sort Strategy Scan whole list to find smallest/largest element and place item in correct final position (e.g. smallest in first index, largest in last index) Scan for next smallest/largest element among last n – 1 elements and place in correct final position Repeat until list is sorted (i.e. after n – 1 passes)
Selection Sort Example |7 8 3 1 6 n=5 1 | 8 3 7 6 n-1 1 3 | 8 7 6 n-2 1 3 6 | 7 8 2 1 3 6 7 | 8 1 1 3 6 7 8|
Selection Sort Analysis
Bubble Sort Strategy Traversing a collection of elements Compare adjacent elements of the list and swapping them if out of order Doing it repeatedly, end up “bubbling up” the largest element to the last position on the list
Bubble Sort Example 7 8 3 1 6 3 1 6 7 8 7 8 3 1 6 1 3 6 7 8 7 3 8 1 6 1 3 6 7 8 (2 comp) 7 3 1 8 6 7 3 1 6 8 (4 comp) 1 3 6 7 8 1 3 6 7 8 (1 comp) 7 3 1 6 8 3 7 1 6 8 3 1 7 6 8 3 1 6 7 8 (3 comp)
Bubble Sort Analysis Time complexity is O(n2) for all cases – best case, worst case, or average case Not a practical sorting algorithm when n is large.
Merge Sort Strategy Divide and conquer method Given an array with n items (let n be a power of 2): Divide the array into two subarrays each with n/2 items. Conquer (solve) each subarray by sorting it. Unless the array is sufficiently small, use recursion to do this. Combine the solutions to the subarrays by merging them into a single sorted array.
Merge Sort Example
Merge Sort Analysis
Quick Sort Strategy Divide and conquer method Similar to merge sort; however, it divides its input’s elements according to their value in the array Partition is used; where all elements before a pivot point s is smaller than or equal to that pivot and all the elements after the pivot point s is larger than or equal to that pivot. A[0] … A[s – 1] A[s] A[s + 1] … A[n – 1] all are ≤ A[s] all are ≥ A[s]
Quick Sort Example
Quick Sort Analysis Worst-Case: O(n2). Call Partition O(n) times, each time takes O(n) steps. So O(n2), and it is worse than Merge Sort in the Worst-Case. Best-Case & Average-Case: O(nLogn). Split the list evenly each time.