Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Fib (5)
Fib (4)
Fib (3)
Fib (3)
Fib (2)
Fib (2)
Fib (1)
Fib (2)
Fib (1)
xy
Factorial (5)
35
3 *
Factorial (4)
34 33 32 31
Factorial (3)
Factorial (2)
Factorial (1)
T(2k) = 18 + T(2k-1) = 18 + (18 + T(2k-2)) = 18 + 18 + (18 + T(2k-3)) = .. = .. = 18k + T(2k-k) = 18k + T(20) = 18k + T(1)
Since T(1) is add number, the running time of T(1) is: T(1) = 20 + T(0) = 20 + 5 = 25 Therefore, T(2k) = 18k + 25
T(n) = 18log n + 25
T(2k) = 18 + 18 + 18 + 18 + T(2k-4)
T(2k) = 18 + 18 + 18 + 18 + T(2k-4) + .+ 18 + T(2k-k) T(2k) = 18n + T(20) = = 18n + T(1) = 18k + 25 18logn + 25
- This is an algorithm which is naturally stated recursively - First, recall the iterative solution
Mergesort
- Sometimes a recursive solution is in fact the fastest solution - An important example of this is mergesort one of the fastest known "comparison based" sorting algorithms also extremely fast in practice
Mergesort
- Main idea break the array into two unsorted arrays of equal size sort each side recursively
Mergesort
- For example, on array A = { 5, 9, 3, 13, 2, 6, 4, 1, 3, 7 } left = { 5, 9, 3, 13, 2 } right = { 6, 4, 1, 3, 7 } Recursively sort left to {2, 3, 5, 9, 13} Recursively sort right to {1, 3, 4, 6, 7} Merge the two sorted arrays into a single sorted array: { 1, 2, 3, 3, 4, 5, 6, 7, 9, 13 }
Mergesort: merging
- Aside from the recursion, the only operation which needs to be accomplished is to merge two sorted lists
- Idea: maintain a "pointer" into each sorted array at each step, append the smallest element pointed to onto the final array
Mergesort: merging
Step 1:
Step 2:
Step 10:
Mergesort: merging
vector< int> merge( const vector< int>& L, const vector< int>& R) { int Lptr= 0, Rptr= 0; vector< int> A; while (Lptr< L.size() || Rptr< R.size()) { if ((Lptr< L.size()) && ((Rptr>= R.size() || L[Lptr]<= R[Rptr]))) { A.push_back( L[Lptr]); Lptr++; } else { A.push_back(R[Rptr]); Rptr++; } } return A; }
Mergesort
- The
- This is a by far faster than some other sorts like bubble sort or insertion sort algorithm