[Tutor] stable algorithm

David Hláčik david at hlacik.eu
Sun Dec 14 17:08:24 CET 2008


>
> Does that mean its homework?
>
Hi,

yes it is homework , this is result :

#! /usr/bin/python
def sort(numbers):
        "sort n positive integers in O(n) provided that they are all < n^2"
        N = len(numbers) # get size of test numbers

        buckets_mod = [[] for i in xrange(N)]
        buckets_sorted = [[] for i in xrange(N+1)]

        # group numbers to buckets (list of numbers) with common modulus
        for n in numbers:
                buckets_mod[n % N].append(n)
        print "buckets_mod: %s" % buckets_mod

        # check numbers in buckets
        for l in buckets_mod:
                for n in l:
                        # place number into bucket number grouped by
result of division
                        buckets_sorted[n / N].append(n)
        print "buckets_sorted: %s" % buckets_sorted

        # search through sorted buckets and return list of sorted numbers
        return [n for l in buckets_sorted for n in l]

Hope it is optimal and OK, what you guys thinks?

Thanks in advance!


More information about the Tutor mailing list