Daa Unit II
Daa Unit II
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
if a < bd
T(n) = If a = bd
if a > bd
Mergesort
• Split array A[0..n-1] into about equal halves and make copies of each half
in arrays B and C
Once all elements in one of the arrays are processed, copy the
remaining unprocessed elements from the other array into A.
Pseudocode of Mergesort
Pseudocode of Merge
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
12/8/13
Analysis of Mergesort
• All cases have same efficiency: Θ(n log n)
T(n) = 2T(n/2) + Θ(n), T(1) = 0
• Number of comparisons in the worst case is close to
theoretical minimum for comparison-based sorting:
. Space requirement: Θ(n) (not in-place)
• Rearrange the list so that all the elements in the first ‘s’
positions are smaller than or equal to the pivot and all the
elements in the remaining n-s positions are larger than or
equal to the pivot.
Exchange the pivot with the last element in the first subarray
— the pivot is now in its final position.
or i > r
or j = l
<
Improvements:
• better pivot selection: median of three partitioning
• elimination of recursion
These combine to 20-25% improvement
Considered the method of choice for internal sorting of large
files (n ≥ 10000)
Binary Search
public static int binarySearch(int [ ] list, int listLength, int key) {
int first = 0, last = listLength - 1;
int mid;
boolean found = false;
12/8/13
Contd..
12/8/13
Assignment questions
1. What is brute-force method? Write a brute-force string
matching algorithm. Analyze its complexity.
2. Write the quick sort algorithm. Analyze its efficiency.
Apply the algorithm to sort the list 4, 1, 6, 3, 9, 2, 7, 5 .
3. Using quick sort algorithm. Arrange the letters of the
word a” EXAMPLE” in alphabetical order .
4. Using quick sort algorithm. Arrange the letters of the
word a” QUESTION” in alphabetical order.
5. Write the algorithm for binary search and find the
average case efficiency.
1
-
2
0
Contd..
6. Discuss the merge sort algorithm with recursive tree
and its efficiency. Apply the same algorithm to sort the
list {4,6,1,3,9,5}
7. Using bubble sort algorithm. Arrange the letters of the
word a” QUESTION” in alphabetical order
8. Using bubble sort algorithm. Arrange the letters of the
word a” EXAMPLE” in alphabetical order
9. Give the general divide and conquer recurrence and
explain the same. Give the master‟s theorem.
10. What is divide-and conquer technique? Explain the
concept of divide and conquer methodology indicating
three major variations.
Thank You..