Reputation: 123
I was Trying Merge sort but Not getting proper output
getting output [0,0,0,0,0,0,0]
value is not merging in my array b why ? what's wrong in the code?
can anyone please help to Understand this?
def merge(a, low, high, mid):
b = [0]*len(a)
i = low
j = mid+1
k = low
while (i <= mid and j <= high):
if a[i] < a[j]:
b[k] = a[i]
i += 1
k += 1
else:
b[k] = a[j]
j += 1
k += 1
while(i <= mid):
b[k] = a[i]
i += 1
k += 1
while(j <= high):
b[k] = a[j]
j += 1
k += 1
for i in range(0, len(a)):
a[i] = b[i]
def mergeSort(a, low, high):
if (low < high):
mid = (low+high)//2
mergeSort(a, low, mid)
mergeSort(a, mid+1, high)
merge(a, low, high, mid)
arr = [55, 3, 100, 32, 5, 1, 22]
low = 0
high = len(arr)-1
mergeSort(arr, low, high)
print(arr)
Upvotes: 0
Views: 33
Reputation: 3833
Your merge
copies in a
all the values from b
, but only a part of b
has been populated, so the next iteration will find a few zeros in a
and soon a
will only contain zeros.
Just replace
for i in range(0, len(a)):
a[i] = b[i]
with
for i in range(low, high+1):
a[i] = b[i]
Upvotes: 2