Week 3 - Part 1
Week 3 - Part 1
Output: permutation 〈a'1, a'2, …, a'n〉 such that a'1 ≤ a'2 ≤ … ≤ a'n .
Example:
Input: 8 2 4 9 3 6
Output: 2 3 4 6 8 9
The problem of sorting
Stability: Stable sorting algorithms maintain the relative order of records with equal keys (i.e.,
value)
● A sorting algorithm is stable if whenever there are two records, e.g., R and S, with
the same key, and R appears before S in the original list, then R will always appear
before S in the sorted lists.
In-Place: In-place sorting algorithms do not need an extra space and produces an output in the same
memory that contains the data by transforming the input ‘in-place’.
for i = 1 to n do:
minIndex = i
for j = i + 1 to n do:
minIndex = j
11 25 12 22 64
11 12 25 22 64
11 12 22 25 64
11 12 22 25 64
Running Time for Selection Sort
● T(n) = time to sort an interval of length n.
● How long does it take to find the minimum?
○ Θ(n).
Running Time for Selection Sort
● T(n) = time to sort an interval of length n.
● How long does it take to find the minimum?
○ Θ(n).
● T(n) = n + T(n-1)
● T(1) = 1
● Solution?
○ 𝑇(𝑛) = Θ(𝑛2).
● What if the input is sorted?
○ Still Θ(𝑛2)
Insertion Sort
Can we do better?
● For example, if the input array is already sorted; the algorithm should run in time Θ
(n).
● Yes! Insertion Sort.
Insertion Sort
Example of Insertion Sort
Correctness of Insertion Sort
We will show (by induction) that, for each i, the algorithm correctly sorts the subarray
A[1…i].
13 11
7 9
2 1
Merging Two Sorted Arrays
T(n) = Θ(n lg n)
Sorting Overview
● Selection-Sort:
○ Very simple to implement.
○ (In-place) Does not use additional memory.
○ For all inputs, runs in time Θ(𝑛2).
Sorting Overview
● Selection-Sort:
○ Very simple to implement.
○ (In-place) Does not use additional memory.
○ For all inputs, runs in time Θ(𝑛2).
● Insertion-Sort:
○ Relatively easier to implement.
○ In-place.
○ Runs in time O(𝑛2)
○ Or, O(n + I) where I is the # of inversions.
○ So it runs faster on nearly sorted arrays.
Sorting Overview
● Selection-Sort:
○ Very simple to implement.
○ In-place (Does not use additional memory).
○ For all inputs, runs in time Θ(𝑛2).
● Insertion-Sort:
○ Relatively easier to implement.
○ In-place.
○ Runs in time O(𝑛2)
○ Or, O(n + I) where I is the # of inversions.
○ So it runs faster on nearly sorted arrays.
● Merge-Sort:
○ More difficult to implement.
○ Needs 2x extra memory for merging step.
○ Runs always in time Θ (𝑛 lg 𝑛) .