Skip to content

Instantly share code, notes, and snippets.

@moeinxyz
Last active April 18, 2022 22:28
Show Gist options
  • Save moeinxyz/156741f6fdd95701ee902d947361b8f1 to your computer and use it in GitHub Desktop.
Save moeinxyz/156741f6fdd95701ee902d947361b8f1 to your computer and use it in GitHub Desktop.
def gnome_sort(array):
size = len(array)
pos = 0
comparisons = 0
while pos < size:
comparisons += 1
if pos == 0 or array[pos] >= array[pos - 1]:
pos += 1
else:
array[pos], array[pos - 1] = array[pos - 1], array[pos]
pos -= 1
return comparisons
def improved_gnome_sort(array):
size = len(array)
prev_pos = pos = 0
comparisons = 0
direction = 1
while pos < size:
comparisons += 1
if pos == 0 or array[pos] >= array[pos - 1]:
if direction == -1:
pos = prev_pos + 1
direction = 1
else:
pos += 1
else:
array[pos], array[pos - 1] = array[pos - 1], array[pos]
if direction == 1:
prev_pos = pos
direction = -1
pos -= 1
return comparisons
input_array = list(range(10000, 0, -1))
print("It took normal gnome sort %s comparisons" % (gnome_sort(input_array)))
print(input_array)
input_array = list(range(10000, 0, -1))
print("It took improved gnome sort %s comparisons" % (improved_gnome_sort(input_array)))
print(input_array)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment