python - Problems with the pseudocode in CLRS -
i'm using clrs introduction algorithms. trying implement algorithm written in pseudocode in book, in python. however, i'm having problems because book starts indexing 1. how implemented merge sort, doesn't work correctly:
def mergesort(a, start, end): if(start < end): middle = math.floor((start + end)/2) mergesort(a, start, middle) mergesort(a, middle + 1, end) merge(a, start, middle, end) def merge(a, start, middle, end): n1 = middle - start + 1 n2 = end - middle l = [0] * n1 r = [0] * n2 in range(0, n1): l[i] = a[start + - 1] j in range(0, n2): r[j] = a[middle + j] = 0 j = 0 k in range(start, end): if(i >= n1): a[k] = r[j] j += 1 elif(j >= n2): a[k] = l[i] += 1 elif(l[i] <= r[j]): a[k] = l[i] += 1 else: a[k] = r[j] j += 1
how should convert pseudocode python code without having these (off-by-one?) errors ?
there small error easy on , indices in line of merge function
a[start + - 1] should start + i
because begin looping 0 , value of start can 0 makes start + -1
, iteration
start == == 0
your index becomes -1 last element of list in python
and in final loop of merge function range should
for k in range(start, end+1) because has iterated start until end inclusive
this should run fine
import math def mergesort(a, start, end): if(start < end): middle = math.floor((start + end)/2) mergesort(a, start, middle) mergesort(a, middle + 1, end) merge(a, start, middle, end) def merge(a, start, middle, end): n1 = middle - start + 1 n2 = end - middle l = [0] * n1 r = [0] * n2 in range(0, n1): l[i] = a[start + ] j in range(0, n2): r[j] = a[middle + j+1] = 0 j = 0 k in range(start, end+1): if(i >= n1): a[k] = r[j] j += 1 elif(j >= n2): a[k] = l[i] += 1 elif(l[i] <= r[j]): a[k] = l[i] += 1 else: a[k] = r[j] j += 1 arr=[4,8,5,6,9,8,1] mergesort(arr,0,len(arr)-1) print(arr)
Comments
Post a Comment