Menu Bar

Friday, June 10, 2016

Sleep Sort Algorithm

Source: I used to run this program

https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort


#!/usr/bin/env python

from time import sleep
from threading import Timer

def sleep_sort(values):
        sleep_sort.result = []
        def add1(x):
                print 'Appending value in list -> %d' % x
                sleep_sort.result.append(x)
        mx = values[0]
        for value in values:
                if mx < value: mx = value
                print 'Calling Timer for value = %d' % value
                Timer(value, add1, [value]).start()
        sleep(mx+1)
        return sleep_sort.result

if __name__ == '__main__':
        x = [3,1,4, 1, 8, 5, 0]
        if sleep_sort(x) == sorted(x):
                print('Sleep sort worked for: ', x)
        else:
                print('Sleep sort FAILED for: ', x)

No comments:

Post a Comment