previous |
start |
next
Analyzing Merge Sort Algorithm
- In an array of size n, count how many times an array
element is visited
- Assume n is a power of 2: n =
2m
- calculate the number of visits create the two sub-arrays and
then merge the two sorted arrays
- 3 visits to merge each element or 3n visits
- 2n visits to create the two sub-arrays
- total of 5n visits
- Let T(n) denote the number of visits to sort an array of
n elements then
- T(n) = T(n/2) + T(n/2) + 5n or
- T(n) = 2*T(n/2) + 5n
- The visits for an array of size n/2 is
T(n/2) = 2*T(n/4) +
5n/2
- So T(n) = 2 * 2*T(n/4) +5n +
5n
- The visits for an array of size n/4 is
T(n/4) = 2*T(n/8) +
5n/4
- So T(n) = 2 * 2 * 2*T(n/8) + 5n +
5n + 5n
- Repeating the process k
times: T(n) =
2kT(n/2k)
+5nk
- since n = 2m, when k =
m: T(n) =
2mT(n/2m)
+5nm
- T(n) = nT(1) +5nm
- T(n) = n +
5nlog2(n)
- To establish growth order
- Drop the lower-order term n
- Drop the constant factor 5
- Drop the base of the logarithm since all logarithms are related
by a common factor
- We are left with n log(n)
- Using big-Oh notation: The number of visits is O(
nlog(n) )
previous |
start |
next