CST-370 Week 4
This week, I learned about the merge sort algorithm, an algorithm that uses the divide-and-conquer technique for sorting.
Basic Idea
1. Split the input array into two halves
2. Sort the first half of the input array recursively
3. Sort the second half of the input array recursively
4. Merge the two sorted halves together
Merge of the two sorted array B and C:
1) Compare the first element in arrays B and C
2) The smaller element is added to array A
3) The index of the array with the smaller element is increased by one (pointing to the next element)
4) Repeat until all elements from B and C are copied into A (sorted)
Example:
Time Analysis Of Merge Sort
Algo: Mergesort(A[0, ... n-1])
if n > 1
copy A[0..[n/2]] to B[0..[n/2]-1]
copy A[n/2.. n-1] to C[0.. [n/2] - 1]
Mergesort(B[0..[n/2]-1]
Mergesort(C[0..[n/2]-1])
Merge(B, C, A)
Recurrence relation:
T(n) = aT(n/b) + f(n) where f(n) is an element of Big Theta(n^d), d >= 0
A is 2 since we are making two recursive calls. B is 2 since we are dividing the input size by two.
T(n) = 2*T(n/2) + n-1
-> 2*T(n/2) + O(n^1) <-- Big theta
a = 2, b = 2, d = 1
Case 2: a = b^d => 2 = 2^1 => 2 = 2
Big Theta(nlogn)

Comments
Post a Comment