[Tutor] A mergesort
D.V.N.Sarma డి.వి.ఎన్.శర్మ
dvnsarma at gmail.com
Sat Aug 31 18:30:23 CEST 2013
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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130831/b21b1043/attachment.html>
More information about the Tutor
mailing list