Skip to content

Commit ec1e51c

Browse files
Created Divide and Conquer Algorithm
1 parent 749aa23 commit ec1e51c

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Divide and Conquer Algorithms
2+
3+
Divide and Conquer is a paradigm for solving problems that involves breaking a problem into smaller sub-problems, solving the sub-problems recursively, and then combining their solutions to solve the original problem.
4+
5+
## Merge Sort
6+
7+
Merge Sort is a popular sorting algorithm that follows the divide and conquer strategy. It divides the input array into two halves, recursively sorts the halves, and then merges them.
8+
9+
**Algorithm Overview:**
10+
- **Divide:** Divide the unsorted list into two sublists of about half the size.
11+
- **Conquer:** Recursively sort each sublist.
12+
- **Combine:** Merge the sorted sublists back into one sorted list.
13+
14+
```python
15+
def merge_sort(arr):
16+
if len(arr) > 1:
17+
mid = len(arr) // 2
18+
left_half = arr[:mid]
19+
right_half = arr[mid:]
20+
21+
merge_sort(left_half)
22+
merge_sort(right_half)
23+
24+
i = j = k = 0
25+
26+
while i < len(left_half) and j < len(right_half):
27+
if left_half[i] < right_half[j]:
28+
arr[k] = left_half[i]
29+
i += 1
30+
else:
31+
arr[k] = right_half[j]
32+
j += 1
33+
k += 1
34+
35+
while i < len(left_half):
36+
arr[k] = left_half[i]
37+
i += 1
38+
k += 1
39+
40+
while j < len(right_half):
41+
arr[k] = right_half[j]
42+
j += 1
43+
k += 1
44+
45+
arr = [12, 11, 13, 5, 6, 7]
46+
merge_sort(arr)
47+
print("Sorted array:", arr)
48+
```
49+
50+
## Complexity Analysis
51+
- **Time Complexity:** O(n log n) in all cases
52+
- **Space Complexity:** O(n) additional space for the merge operation
53+
54+
---

0 commit comments

Comments
 (0)