Lecture 3 Sorting Algorithms
Sorting Problem
Input: A sequence of n numbers .
Output: A permutation of the input sequence such that .
Selection Sort
Idea of a selection sort method
- Start with empty hand, all cards on table
- Pick the smallest card from table
- Insert the card into the hand
1 | Selection-Sort(A) |
- total time complexity:
Insertion Sort
Idea of a insertion sort method
- One input each iteration, growing a sorted output list
- Remove one element from input data
- Find the location it belongs within the sorted list
- Repeat until no input elements remain
1 | for i=1 to n |
- total time complexity:
Bubble Sort
Idea of a bubble sort method
- For each pass
- Compare the pair of adjacent item
- Swap them if they are in the wrong order
- Repeat the pass through until no swaps are needed
1 | Bubble-Sort(A) |
- total time complexity:
Merge Sort (Divide-and-Conquer)
Divide and Conquer: an algorithmic technique
- Divide: divide the problem into smaller
subproblems - Conquer: solve each subproblem recursively
- Combine: combine the solution of subproblems into the solution of the original problem
Merge Sort Algorithm
- Divide: divide the array into two subarrays of n/2 numbers each
- Conquer: sort two subarrays recursively
- Combine: merge two sorted subarrays into a sorted array
1 | Merge-Sort(A, l, r) |
T(n) = 2T(n/2) + O(n)
Using the Master Theorem, we can solve this recurrence relation:
- total time complexity:
Master Theorem
Recurrence equation:
Let be a function that return a positive value for every integer . We know that:
- for()
where and are constants, and is a constant.
Then:
- If , then .
- If , then .
- If , then .
Example:
binary search
merge sort
Quick Sort (RAM with Randomization)
Randomized
Randomized algorithms play an important role in computer science, they often simpler, and sometimes can be provably faster as well.
1 | find0(A) |
- When A are all 0, the expected time is O(1)
- When A has only one 0, the expected time is O(n)
- As before, the expected time is O(n)
Quick Sort Algorithm
- Randomly pick an integer p in A, call it the pivot
- Re-arrange the integers in an array A’ such that
- All the integers smaller than p are positioned before p in A’
- All the integers larger than p are positioned after p in A’
- Sort the part of A’ before p recursively
- Sort the part of A’ after p recursively
1 | Randomized-Quick-Sort(A, L, R) |
- total time complexity: on average, in the worst case