Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Created May 20, 2011 04:10
Show Gist options
  • Save masahitojp/982338 to your computer and use it in GitHub Desktop.
Save masahitojp/982338 to your computer and use it in GitHub Desktop.
Python でsleep_sort
#!/usr/bin/env python
# coding: utf-8
from multiprocessing import cpu_count, Process, Queue
from os import getpid
from time import sleep
from random import randint
def put_queue(queue, num):
sleep(num)
queue.put(num)
def sleep_sort(arr):
"""
[Genius sorting algorithm: Sleep sort ]
http://dis.4chan.org/read/prog/1295544154
>>> sleep_sort([])
[]
>>> sleep_sort([9, 4, 3, 6, 7, 8, 2, 5, 1, 10])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
"""
q = Queue()
process_list = []
for i in arr:
process_list.append( Process(target=put_queue, args=(q, i,)))
for p in process_list:
p.start()
sort_result = [q.get() for i in range(len(arr))]
for p in process_list:
p.join()
return sort_result
if __name__ == '__main__':
print('pid: %d' % getpid())
c = cpu_count()
print('num of cpu: %d' % c)
max_num = 10
random_array = [randint(1,max_num) for r in range(max_num)]
print("before:")
print( random_array )
print("after:")
print( sleep_sort(random_array) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment