DAA Lecture 02
DAA Lecture 02
Peshawar, Pakistan
Lecture 2
waseem@uetpeshawar.edu.pk
Divide and Conquer Approach
waseem@uetpeshawar.edu.pk 2
Divide and Conquer Approach
Many useful algorithms are recursive in structure
To solve a given problem, they call themselves recursively one or more times to deal with
closely related sub-problems
These algorithms break the problem into several sub-problems that are similar to the
original problem but smaller in size, solve the sub-problems recursively, and then combine
these solutions to create a solution to the original problem
waseem@uetpeshawar.edu.pk 3
Divide and Conquer Approach
The divide-and-conquer paradigm involves three steps at each level of the recursion:
➢ Divide the problem into a number of sub-problems that are smaller instances of the same
problem
➢ Combine the solutions to the sub-problems into the solution for the original problem
waseem@uetpeshawar.edu.pk 4
Merge Sort
Split array A[0..n-1] in two about equal halves and make copies of each half in arrays B & C
❑ Copy the smaller of the two into A, while incrementing the index indicating the unprocessed portion of that array
➢ Once all elements in one of the arrays are processed, copy the remaining unprocessed
elements from the other array into A
waseem@uetpeshawar.edu.pk 5
Merge Sort Example
waseem@uetpeshawar.edu.pk 6
Merge Sort Example
waseem@uetpeshawar.edu.pk 7
Merge Sort
waseem@uetpeshawar.edu.pk 8
Merge Sort
waseem@uetpeshawar.edu.pk 9
Binary Search Example
waseem@uetpeshawar.edu.pk 10
Binary Search Example
waseem@uetpeshawar.edu.pk 11
Binary Search Example
waseem@uetpeshawar.edu.pk 12
Binary Search
waseem@uetpeshawar.edu.pk 13
Binary Search
waseem@uetpeshawar.edu.pk 14
Quick Sort
Select a pivot (partitioning element) – here, the first element
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 (see next slide for an algorithm)
Exchange the pivot with the last element in the first (i.e., ≤) subarray — the pivot is now in
its final position
waseem@uetpeshawar.edu.pk 15
Quick Sort
waseem@uetpeshawar.edu.pk 16
Analysis of Quick Sort
Divide-and-conquer:
➢ Partition array into two subarrays, recursively sort
waseem@uetpeshawar.edu.pk 17