Divide Conquer
Divide Conquer
Divide Conquer
Practice problems:
Instructions:
1. Do not adopt unfair means. 10 marks will be deducted from the final marks for
adopting unfair means.
2. No more than 40% marks for uncompilable codes.
Recursion Tree:
2. X^Y
Hint:
100 100
3100 = 350 . 350 = (3 2 ). (3 2 )
3. Merge sort
4. Count Inversion
https://www.cp.eng.chula.ac.th/~prabhas//teaching/algo/algo2008/count-inv.htm
The sequence 2, 4, 1, 3, 5 has three inversions (2,1), (4,1), (4,3).
The idea is similar to "merge" in merge-sort. Merge two sorted lists into one output list,
but we also count the inversion.
5. Quick Sort
The quick sort uses divide and conquer just like merge sort but without using additional
storage.
The steps are:
1. Select an element q, called a pivot, from the array. In this algorithm we have
chosen the last index as the pivot.
Divide and conquer
2. The PARTITION function finds the location of the pivot in such a way that all the
elements smaller than the pivot is on the left side and all the element on the
right-hand side of the pivot is greater in value. (Items with equal values can go
either way).
3. Recursively call the QUICKSORT function which perform quicksort on the array
on the left side of the pivot and then on the array on the right side, thus dividing
the task into sub tasks. This is carried out until the arrays can no longer be split.
Implement Quick sort algorithm. The pseudo code is given below:
6. Binary Search
Divide and conquer
Number of Elements: 5
Enter elements: 3 4 5 7 2 4 found in index 1
Key: 4
Number of Elements: 5
Enter elements: 3 4 5 7 2 14 not found
Key: 14
7.
Write a function print_odd using divide-and-conquer algorithm to print the odd numbers of
an array of n integers.
8.
Write a function calc_sum using divide-and-conquer algorithm to calculate the sum of an
array of n integers.
9.
Write a function calc_sum using divide-and-conquer algorithm to calculate the sum of the
even numbers of an array of n integers.
Divide and conquer
3
Algolab Alg
Algorithms
Algeria
4
Algolab No common prefix
Algorithms
Algeria
UIU
Divide and conquer
Running time:
𝑛
𝑇(𝑛) ≤ 2𝑇 ( ) + 𝑂(𝑛 log 𝑛) 𝑇(𝑛) = 𝑂(𝑛 log 2 𝑛)
2
• Each recursive returns two lists: all points sorted by y coordinate, and all points sorted
by x coordinate.
• Sort by merging two pre-sorted lists.
𝑛
• 𝑇(𝑛) ≤ 2𝑇 ( 2) + 𝑂(𝑛) 𝑇(𝑛) = 𝑂(𝑛 log 𝑛)
Reference:
• Slides of Dr. Md. Abul Kashem Mia, Professor, CSE Dept, BUET