Skip to content

Commit 87ac4b9

Browse files
committed
adding smooth_sort.py represent smooth sort algorithm
1 parent 102e9a3 commit 87ac4b9

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

sorts/smooth_sort.py

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
def smooth_sort(unsorted):
2+
"""
3+
Pure implementation of the smooth sort algorithm using Leonardo numbers in Python
4+
:param unsorted: unordered mutable collection
5+
:return: the same collection ordered in ascending order
6+
7+
Examples:
8+
>>> smooth_sort([0, 5, 3, 2, 2])
9+
[0, 2, 2, 3, 5]
10+
11+
>>> smooth_sort([])
12+
[]
13+
14+
>>> smooth_sort([-2, -5, -45])
15+
[-45, -5, -2]
16+
"""
17+
18+
def leonardo(leonardo_number):
19+
"""
20+
leonardo number represent numbers in pattern where third number is the sum of
21+
2 preceding numbers plus 1 also leonardo number used in heap construction
22+
every number represent size of tree within the heap
23+
they are used in heapify using max heap approach which we will see later
24+
"""
25+
if leonardo_number < 2:
26+
return 1
27+
return leonardo(leonardo_number - 1) + leonardo(leonardo_number - 2) + 1
28+
29+
def heapify(start, end):
30+
i = start
31+
j = 0
32+
k = 0
33+
34+
while k < end - start + 1:
35+
if k & 0xAAAAAAAA:
36+
j = j + i
37+
i = i >> 1
38+
else:
39+
i = i + j
40+
j = j >> 1
41+
42+
k = k + 1
43+
44+
while i > 0:
45+
j = j >> 1
46+
k = i + j
47+
while k < end:
48+
if unsorted[k] < unsorted[k - i]:
49+
break
50+
unsorted[k], unsorted[k - i] = unsorted[k - i], unsorted[k]
51+
k = k + i
52+
53+
i = j
54+
55+
n = len(unsorted)
56+
if n <= 1:
57+
return unsorted
58+
59+
p = n - 1
60+
q = p
61+
r = 0
62+
while p > 0:
63+
if (r & 0x03) == 0:
64+
heapify(r, q)
65+
66+
if leonardo(r) == p:
67+
r = r + 1
68+
else:
69+
r = r - 1
70+
q = q - leonardo(r)
71+
heapify(r, q)
72+
q = r - 1
73+
r = r + 1
74+
75+
unsorted[0], unsorted[p] = unsorted[p], unsorted[0]
76+
p = p - 1
77+
78+
for i in range(n - 1):
79+
j = i + 1
80+
while j > 0 and unsorted[j] < unsorted[j - 1]:
81+
unsorted[j], unsorted[j - 1] = unsorted[j - 1], unsorted[j]
82+
j = j - 1
83+
84+
return unsorted
85+
86+
87+
if __name__ == "__main__":
88+
user_input = input(
89+
"Enter numbers separated by a comma (or press Enter to exit):\n"
90+
).strip()
91+
if not user_input:
92+
print(smooth_sort([]))
93+
else:
94+
unsorted = [int(item) for item in user_input.split(",")]
95+
print(smooth_sort(unsorted))

0 commit comments

Comments
 (0)