Last active
November 8, 2019 02:01
-
-
Save mauriciogardini/bccaeb31874c66681e19a8d93bb60670 to your computer and use it in GitHub Desktop.
Shell Sort implementation in Python
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
from math import ceil | |
def _return_list_gaps(size, ratio=None): | |
gaps = list() | |
if not ratio: | |
ratio = 2.2 | |
while size > 1: | |
size = ceil(size / ratio) | |
gaps.append(size) | |
return gaps | |
def shell_sort(array, decrescent=False, gaps=None, ratio=None): | |
if len(array) <= 1: | |
return array | |
# If no custom list of gaps was passed, defaults to the 2.2 ratio, and | |
# builds a list of gaps to this ratio | |
if not gaps: | |
gaps = _return_list_gaps(len(array), ratio=ratio) | |
# Guarantees that the list is in decrescent order | |
gaps = sorted(gaps, reverse=True) | |
for gap in gaps: | |
for x in range(gap, len(array)): | |
temp = array[x] | |
y = x | |
while y > 0 and ((decrescent and y >= gap and array[y - gap] < temp) or | |
(not decrescent and y >= gap and array[y - gap] > temp)): | |
array[y] = array[y - gap] | |
y = y - gap | |
array[y] = temp | |
return array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment