Part II
Part II
BINARY SEARCH
1. Initialization:
3. Comparison:
Compare the value at mid with the target
If the middle element equals the target, return mid.
If the middle element is greater than the target, narrow the search to the left half by
setting high = mid - 1.
If the middle element is less than the target, narrow the search to the right half by
setting low = mid + 1.
4. Repeat:
Continue this process until low > high or the target is found.
MERGE SHORT
1. Divide:
If the list has more than one element, divide it into two halves.
2. Conquer (Recursion):
Recursively apply merge sort to each half until the list is reduced to individual
elements (base case).
3. Merge:
Merge the sorted halves back together into a single sorted list.
QUICK SORT
Time Complexity
Best/Average Case: O(nlogn)O(n \log n)O(nlogn
Worst Case: O(n2)O(n^2)O(n2) (occurs when pivot is poorly chosen, e.g.,
smallest or largest element)
Space Complexity: O(logn)O(\log n)O(logn) (for recursion stack)
In-Place Sorting: Uses no extra space for sorting, making it memory-efficient.
Chapter 5: Backtracking
1. Choose a Pivot: Select an element from the array (commonly the first, last, or middle
element).
2. Partition: Rearrange the array such that:
All elements less than the pivot go to its left.
All elements greater than the pivot go to its right.
3. Recursion: Apply the same process to the left and right subarrays (excluding the pivot).
4. Base Case: Stop when the subarray has 0 or 1 element (already sorted).
1. Memoization
Starts solving from the main problem, recursively breaking it into subproblems.
Caches results of subproblems as they are computed.
Reuses cached results for repeated subproblems.
2. Tabulation
Builds the solution for smaller subproblems first and combines them iteratively.
Avoids function call overhead and recursion stack usage.