I have been searching for mergesort implimentations in python and came
across
this.

def merge(a, b):
if len(a)*len(b) == 0:
return a+b

v = (a[0] < b[0] and a or b).pop(0)
return [v] + merge(a, b)

def mergesort(lst):
if len(lst) < 2:
return lst

m = len(lst)/2
return merge(mergesort(lst[:m]), mergesort(lst[m:]))

mlst = [10, 9, 8, 4, 5, 6, 7, 3, 2, 1]
sorted = mergesort(mlst)
print sorted

Besides using recursion in merge function also, it has somethings
intresting.

Especially the statement

v = (a[0] < b[0] and a or b).pop(0)

gives a.pop(0), if a[0] < b[0] otherwise b.pop(0).

We have to look at the statement as

v = ((a[0] < b[0] and a) or b).pop(0)


regards,
Sarma.
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to