|
| 1 | +# 📌 Merge Sort Algorithm |
| 2 | +# Language: Python |
| 3 | +# Category: Sorting |
| 4 | +# Time Complexity: O(n log n) |
| 5 | +# Space Complexity: O(n) |
| 6 | + |
| 7 | +""" |
| 8 | +Merge Sort is a classic Divide and Conquer algorithm. |
| 9 | +It works in three main steps: |
| 10 | +1. Divide: Split the array into two halves. |
| 11 | +2. Conquer: Recursively sort the two halves. |
| 12 | +3. Combine: Merge the two sorted halves into a single sorted array. |
| 13 | +""" |
| 14 | + |
1 | 15 | def merge_sort(arr): |
| 16 | + """ |
| 17 | + Sorts the input list 'arr' using the Merge Sort algorithm. |
| 18 | + :param arr: list of elements (int/float) to be sorted |
| 19 | + :return: sorted list |
| 20 | + """ |
| 21 | + # Base condition: if array has 0 or 1 elements, it's already sorted |
2 | 22 | if len(arr) <= 1: |
3 | 23 | return arr |
| 24 | + |
| 25 | + # Step 1: Divide the array into two halves |
4 | 26 | mid = len(arr) // 2 |
5 | 27 | left_half = merge_sort(arr[:mid]) |
6 | 28 | right_half = merge_sort(arr[mid:]) |
| 29 | + |
| 30 | + # Step 2: Merge the sorted halves |
7 | 31 | return merge(left_half, right_half) |
8 | 32 |
|
| 33 | + |
9 | 34 | def merge(left, right): |
| 35 | + """ |
| 36 | + Merges two sorted lists 'left' and 'right' into a single sorted list. |
| 37 | + :param left: sorted list |
| 38 | + :param right: sorted list |
| 39 | + :return: merged sorted list |
| 40 | + """ |
10 | 41 | merged = [] |
11 | 42 | i = j = 0 |
| 43 | + |
| 44 | + # Compare elements of both halves and add the smaller one |
12 | 45 | while i < len(left) and j < len(right): |
13 | 46 | if left[i] <= right[j]: |
14 | 47 | merged.append(left[i]) |
15 | 48 | i += 1 |
16 | 49 | else: |
17 | 50 | merged.append(right[j]) |
18 | 51 | j += 1 |
| 52 | + |
| 53 | + # If there are remaining elements in left or right, add them |
19 | 54 | merged.extend(left[i:]) |
20 | 55 | merged.extend(right[j:]) |
| 56 | + |
21 | 57 | return merged |
22 | 58 |
|
| 59 | + |
| 60 | +# 🧪 Example usage |
23 | 61 | if __name__ == "__main__": |
24 | | - arr = list(map(int, input("Enter numbers separated by space: ").split())) |
25 | | - sorted_arr = merge_sort(arr) |
26 | | - print("Sorted array:", sorted_arr) |
| 62 | + sample_array = [38, 27, 43, 3, 9, 82, 10] |
| 63 | + print("Original array:", sample_array) |
| 64 | + sorted_array = merge_sort(sample_array) |
| 65 | + print("Sorted array:", sorted_array) |
0 commit comments