Skip to content

Instantly share code, notes, and snippets.

@mauriciogardini
Created November 1, 2019 01:23
Show Gist options
  • Save mauriciogardini/8dd28c0cd46e5ee778be856fc27c00e6 to your computer and use it in GitHub Desktop.
Save mauriciogardini/8dd28c0cd46e5ee778be856fc27c00e6 to your computer and use it in GitHub Desktop.
Selection Sort optimized implementation in Python
def selection_sort_optimized(array, decrescent=False):
if len(array) <= 1:
return array
for x in range(len(array)):
left_swap_index = x
right_swap_index = x
for y in range(x + 1, len(array) - x):
if ((decrescent and array[y] > array[left_swap_index]) or
(not decrescent and array[y] < array[left_swap_index])):
left_swap_index = y
if ((decrescent and array[y] < array[right_swap_index]) or
(not decrescent and array[y] > array[right_swap_index])):
right_swap_index = y
array[x], array[left_swap_index] = array[left_swap_index], array[x]
# If the right swap index wasn't changed from the initial value,
# change it for the left swap index, as the left swap will change
# the right swap target element position.
if right_swap_index == x:
right_swap_index = left_swap_index
array[len(array) - x - 1], array[right_swap_index] = array[
right_swap_index], array[len(array) - x - 1]
# If the last outer loop comparisons were made in a subarray that
# has a length of 1 or lower, no more outer loops are needed.
if len(range(x + 1, len(array) - x)) <= 1:
break
return array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment