|
| 1 | +# funtion to divide the lists in the two sublists |
| 2 | +def merge_sort(list1, left_index, right_index): |
| 3 | + if left_index >= right_index: |
| 4 | + return |
| 5 | + |
| 6 | + middle = (left_index + right_index)//2 |
| 7 | + merge_sort(list1, left_index, middle) |
| 8 | + merge_sort(list1, middle + 1, right_index) |
| 9 | + merge(list1, left_index, right_index, middle) |
| 10 | + |
| 11 | + |
| 12 | + # Defining a function for merge the list |
| 13 | +def merge(list1, left_index, right_index, middle): |
| 14 | + |
| 15 | + |
| 16 | + # Creating subparts of a lists |
| 17 | + left_sublist = list1[left_index:middle + 1] |
| 18 | + right_sublist = list1[middle+1:right_index+1] |
| 19 | + |
| 20 | + # Initial values for variables that we use to keep |
| 21 | + # track of where we are in each list1 |
| 22 | + left_sublist_index = 0 |
| 23 | + right_sublist_index = 0 |
| 24 | + sorted_index = left_index |
| 25 | + |
| 26 | + # traverse both copies until we get run out one element |
| 27 | + while left_sublist_index < len(left_sublist) and right_sublist_index < len(right_sublist): |
| 28 | + |
| 29 | + # If our left_sublist has the smaller element, put it in the sorted |
| 30 | + # part and then move forward in left_sublist (by increasing the pointer) |
| 31 | + if left_sublist[left_sublist_index] <= right_sublist[right_sublist_index]: |
| 32 | + list1[sorted_index] = left_sublist[left_sublist_index] |
| 33 | + left_sublist_index = left_sublist_index + 1 |
| 34 | + # Otherwise add it into the right sublist |
| 35 | + else: |
| 36 | + list1[sorted_index] = right_sublist[right_sublist_index] |
| 37 | + right_sublist_index = right_sublist_index + 1 |
| 38 | + |
| 39 | + |
| 40 | + # move forward in the sorted part |
| 41 | + sorted_index = sorted_index + 1 |
| 42 | + |
| 43 | + |
| 44 | + # we will go through the remaining elements and add them |
| 45 | + while left_sublist_index < len(left_sublist): |
| 46 | + list1[sorted_index] = left_sublist[left_sublist_index] |
| 47 | + left_sublist_index = left_sublist_index + 1 |
| 48 | + sorted_index = sorted_index + 1 |
| 49 | + |
| 50 | + while right_sublist_index < len(right_sublist): |
| 51 | + list1[sorted_index] = right_sublist[right_sublist_index] |
| 52 | + right_sublist_index = right_sublist_index + 1 |
| 53 | + sorted_index = sorted_index + 1 |
| 54 | + |
| 55 | +list1 = [44, 65, 2, 3, 58, 14, 57, 23, 10, 1, 7, 74, 48] |
| 56 | +merge_sort(list1, 0, len(list1) -1) |
| 57 | +print(list1) |
0 commit comments