Loading
Loading
Split into independent halves, solve each, combine the results.
Break the input into parts that can be solved independently, recurse on each, then merge the answers. Unlike dynamic programming the parts do not overlap, so nothing needs to be memoised. The interesting work is usually in the combine step.
The recurrence T(n) = 2·T(n/2) + O(n) resolves to O(n log n). If your combine step is worse than linear, check whether the split is actually buying anything.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
def merge_sort(nums): if len(nums) <= 1: return nums mid = len(nums) // 2 left = merge_sort(nums[:mid]) right = merge_sort(nums[mid:]) return merge(left, right) def merge(left, right): """The combine step — where the real work of divide and conquer lives.""" result = [] i = j = 0 while i < len(left) and j < len(right): # '<=' rather than '<' keeps equal elements in their original # relative order, which is what makes the sort stable. if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result.extend(left[i:]) result.extend(right[j:]) return result| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Merge Sorted Feeds#114 | Medium | Related | |
| Fast Modular Power#129 | Medium | Primary |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in