|
3 | 3 | - Merge sort is a recursive algorithm.
|
4 | 4 | - It starts to divide an array until it divides it into sub-arrays with dimensions of 2.
|
5 | 5 | - Then combine by starting the order from the smallest subarray.
|
6 | | -<img src="https://www.101computing.net/wp/wp-content/uploads/Merge-Sort-Algorithm.png" /> |
| 6 | + |
| 7 | +```python |
| 8 | +def merge_sort(arr): |
| 9 | + if len(arr) > 1: |
| 10 | + mid = int(len(arr)/2) |
| 11 | + left_half = arr[:mid] |
| 12 | + right_half = arr[mid:] |
| 13 | + |
| 14 | + merge_sort(left_half) |
| 15 | + merge_sort(right_half) |
| 16 | + |
| 17 | + i = 0 # for left half |
| 18 | + j = 0 # for right half |
| 19 | + k = 0 # all list |
| 20 | + |
| 21 | + while i < len(left_half) and j < len(right_half): |
| 22 | + if left_half[i] < right_half[j]: |
| 23 | + arr[k] = left_half[i] |
| 24 | + i += 1 |
| 25 | + else: |
| 26 | + arr[k] = right_half[j] |
| 27 | + j += 1 |
| 28 | + k = k + 1 |
| 29 | + |
| 30 | + while i < len(left_half): |
| 31 | + arr[k] = left_half[i] |
| 32 | + i += 1 |
| 33 | + k += 1 |
| 34 | + |
| 35 | + while j < len(right_half): |
| 36 | + arr[k] = right_half[j] |
| 37 | + j += 1 |
| 38 | + k += 1 |
| 39 | + |
| 40 | + return arr |
| 41 | + |
| 42 | + |
| 43 | +arr = [3,2,13,4,6,5,7,8,1,20] |
| 44 | +print("Output: ", merge_sort(arr) ) |
| 45 | +``` |
| 46 | +output: |
| 47 | +``` |
| 48 | +[1, 2, 3, 4, 5, 6, 7, 8, 13, 20] |
| 49 | +``` |
| 50 | + |
| 51 | +<img src="https://www.101computing.net/wp/wp-content/uploads/Merge-Sort-Algorithm.png" /> |
0 commit comments