Trying to make a program for Merge Sort in Python. Whre am I going wrong? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Trying to make a program for Merge Sort in Python. Whre am I going wrong?

Here is my code: n = int(input("Enter the number of elements: ")) print() a = [] for i in range(n): a.append(int(input("Enter a number: "))) print("\nUnsorted Array:", a) def merge_sort(a, low, high): if low < high: mid = (low + high) / 2 merge_sort(a, low, mid) merge_sort(a, mid + 1, high) merge(a, low, mid, high) return a def merge(a, low, mid, high): i = low j = mid + 1 k = low temp = [] while i <= mid and j <= high: if a[i] < a[j]: temp[k] = a[i] i += 1 else: temp[k] = a[j] j += 1 k += 1 while i <= mid: temp[k] = a[i] i += 1 k += 1 while j <= high: temp[k] = a[j] j += 1 k += 1 for k in range(low, high+1): a[k] = temp[k] return a print("Sorted Array:", merge_sort(a, 0, n - 1)) I am getting this error while executing the code: IndexError: list assignment index out of range Where am I going wrong? And how do I fix this code?

8th Sep 2021, 4:09 PM
Shreyas Nagle
Shreyas Nagle - avatar
4 Answers
+ 2
This is not good way to asking question, write your code in code section and paste the link here!!! Then it will be easier to debug.
8th Sep 2021, 4:52 PM
Saurabh
Saurabh - avatar
+ 2
The next thing is, what you are trying here is not a merge sort. Maybe something like bubbel sort. For merge sort, you starts with Single elements, merge them to many lists of sorted Pairs, merge them to sortet lists of 4 elements. And so on. Up to one Single sorted list. Later I can give you an example, that shows how it works. I have this only done in Kotlin. But the output shows, how the sub lists will be merged.
8th Sep 2021, 5:05 PM
Coding Cat
Coding Cat - avatar
+ 2
Here is my Kotlin example Have only a look at the output https://code.sololearn.com/cByAnBllM0vB/?ref=app
8th Sep 2021, 5:22 PM
Coding Cat
Coding Cat - avatar