|
| 1 | +""" |
| 2 | +Algorithm: Merge Sort |
| 3 | +
|
| 4 | +Description: |
| 5 | + Merge Sort is a Divide and Conquer sorting algorithm. It divides the input |
| 6 | + array into two halves, recursively sorts them, and then merges the sorted halves |
| 7 | + to produce a fully sorted array. |
| 8 | +
|
| 9 | +Steps: |
| 10 | + 1. Divide the array into two halves until each subarray has one element. |
| 11 | + 2. Recursively sort both halves. |
| 12 | + 3. Merge the sorted halves to form a larger sorted array. |
| 13 | +
|
| 14 | +Use Case: |
| 15 | + Merge Sort is useful when stable sorting is required or when working with |
| 16 | + linked lists, external sorting (large data that doesn’t fit into memory), |
| 17 | + and scenarios where worst-case performance guarantees are important. |
| 18 | +
|
| 19 | +Time Complexity: |
| 20 | + - Best Case: O(N log N) |
| 21 | + - Average Case: O(N log N) |
| 22 | + - Worst Case: O(N log N) |
| 23 | + |
| 24 | +Space Complexity: |
| 25 | + O(N) auxiliary space (due to temporary arrays during merging). |
| 26 | +
|
| 27 | +Stability: |
| 28 | + Merge Sort is a **stable sorting algorithm**, meaning it maintains the |
| 29 | + relative order of equal elements. |
| 30 | +""" |
| 31 | +def merge_sort(arr): |
| 32 | + if len(arr) > 1: |
| 33 | + mid = len(arr) // 2 |
| 34 | + L = arr[:mid] |
| 35 | + R = arr[mid:] |
| 36 | + |
| 37 | + # Recursive calls to sort both halves |
| 38 | + merge_sort(L) |
| 39 | + merge_sort(R) |
| 40 | + |
| 41 | + i = j = k = 0 |
| 42 | + |
| 43 | + # Merge the two halves |
| 44 | + while i < len(L) and j < len(R): |
| 45 | + if L[i] <= R[j]: |
| 46 | + arr[k] = L[i] |
| 47 | + i += 1 |
| 48 | + else: |
| 49 | + arr[k] = R[j] |
| 50 | + j += 1 |
| 51 | + k += 1 |
| 52 | + |
| 53 | + # Copy any remaining elements of L |
| 54 | + while i < len(L): |
| 55 | + arr[k] = L[i] |
| 56 | + i += 1 |
| 57 | + k += 1 |
| 58 | + |
| 59 | + # Copy any remaining elements of R |
| 60 | + while j < len(R): |
| 61 | + arr[k] = R[j] |
| 62 | + j += 1 |
| 63 | + k += 1 |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + arr = [38, 27, 43, 3, 9, 82, 10] |
| 69 | + print("Original array:", arr) |
| 70 | + merge_sort(arr) |
| 71 | + print("Sorted array:", arr) |
| 72 | +# Sorted array: [3, 9, 10, 27, 38, 43, 82] |
0 commit comments