python - 3 Quicksorts Functions - Why is the lambda version slower? Code provided -
i testing quicksort runtimes , noticed lambda version of quicksort slower.
why lambda version noticeably slower? i've tried swapping orders call each , seems stay slower. because redeclaring left, equal, , right each time since filter has assigned (versus appending/in place)?
import timeit def qsort(list): if len(list) > 1: pivot = list[0] left = filter(lambda x: x < pivot, list) equal = filter(lambda x: x == pivot, list) right = filter(lambda x: x > pivot, list) return qsort(left) + equal + qsort(right) else: return list def sort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) elif x > pivot: greater.append(x) return sort(less)+equal+sort(greater) else: return array def partition(array, begin, end): pivot = begin in xrange(begin+1, end+1): if array[i] <= array[begin]: pivot += 1 array[i], array[pivot] = array[pivot], array[i] array[pivot], array[begin] = array[begin], array[pivot] return pivot def quicksort(array, begin=0, end=none): if end none: end = len(array) - 1 if begin >= end: return pivot = partition(array, begin, end) quicksort(array, begin, pivot-1) quicksort(array, pivot+1, end) return array print qsort([5,3,1,5,2,6]) print sort([5,3,1,5,2,6]) print quicksort([5,3,1,5,2,6]) print (timeit.timeit(lambda: qsort([5,3,1,5,2,6]), number=1000)) print (timeit.timeit(lambda: sort([5,3,1,5,2,6]), number=1000)) print (timeit.timeit(lambda: quicksort([5,3,1,5,2,6]), number=1000))
as mentioned in comment, lambdas
require function call expensive. function rewritten using list comprehensions provide time close (sometimes smaller) other functions.
def qsort(ls): if len(ls) > 1: pivot = ls[0] left = [e e in ls if e < pivot] equal = [e e in ls if e == pivot] right = [e e in ls if e > pivot] return qsort(left) + equal + qsort(right) else: return ls
also, changed list
ls
built-in list
isn't shadowed. interesting part that, despite repeated iteration on input, , creation of new intermediate arrays, still comparable in time in-place sorting function. unfortunately, don't know enough explain why. larger lists, seems qsort
performs best , in-place method starts slowing down significantly.
Comments
Post a Comment