.

Sunday, August 2, 2015

Pyhton code for QuickSort using Enumerate


The enumerate function adds an index so you can tell what the index of an item in your iterable is. The xrange function returns an iterable full of numbers. Use it when you want to do something a certain number of times, instead of for each element in an iterable.


__author__ = 'deepika'
def quick_sort(alist):

    if len(alist) > 1:
        pivot_index = len(alist) / 2
        smalleritems = []
        largeritems = []

        for i, val in enumerate(alist):
            if i != pivot_index:
                if val < alist[pivot_index]:
                    smalleritems.append(val)
                else:
                    largeritems.append(val)

        quick_sort(smalleritems)
        quick_sort(largeritems)
        alist[:] = smalleritems + [alist[pivot_index]] + largeritems



alist=[9,8,7,5,0,3]
quick_sort(alist)
print(alist)


Output-
[0, 3, 5, 7, 8, 9]

No comments :

Post a Comment

There was an error in this gadget