Created
July 25, 2017 13:58
-
-
Save konstantint/0c7266a41690917f16ca6fe6d4308ab2 to your computer and use it in GitHub Desktop.
Paul and Simon Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# "Paul-and-Simon sort" | |
# http://fouryears.eu/2017/07/25/sorting-in-linear-time/ | |
# http://www-wjp.cs.uni-saarland.de/publikationen/PS80.pdf | |
# | |
# Copyright 2017, Konstantin Tretyakov | |
# License: MIT | |
from math import log2, ceil | |
def paul_and_simon_sort(a): | |
n, bits = len(a), max([ceil(log2(x)) for x in a]) | |
temp, mask, A, B, result = 0, 0, 0, 0, 0 | |
for x in a: | |
temp = (temp<<(n*(bits+1))) + (1<<bits) + x | |
for i in range(n): | |
A = (A<<(bits+1)) + temp | |
temp = 0 | |
for x in a: | |
temp = (temp<<(bits+1)) + x | |
for i in range(len(a)): | |
B = (B<<((bits+1)*n)) + temp | |
x = A-B >> bits | |
for i in range(n): | |
mask = (mask<<(n*(bits+1))) + 1 | |
for i in range(n): | |
result += x & mask | |
x = x >> (bits+1) | |
r = [result >> (n*(bits+1)*(n-i-1)) & ((1<<(n*(bits+1)))-1) | |
for i in range(n)] | |
a_sorted = [None]*n | |
for i in range(n): | |
a_sorted[r[i]-1] = a[i] | |
return a_sorted |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment