Skip to content

Instantly share code, notes, and snippets.

@victor-iyi
Created August 27, 2017 13:55
Show Gist options
  • Save victor-iyi/21365a1f28d174bb67da243a03b7f8e2 to your computer and use it in GitHub Desktop.
Save victor-iyi/21365a1f28d174bb67da243a03b7f8e2 to your computer and use it in GitHub Desktop.
An optimized sorting algorithm
'''
VICTOR's sorting algorithm!
=> vicSort
HOW vicSort WORKS
not_sorted = [2, 4, 1, 8, 5]
sorted = []
[2] # If no element in `sorted` add the first one
[2, 4] # Is 4>2? (are we at the end of `sorted`?) add to the end
[1,2,4] # Is 1>2? (not greater. Put it in the current index)
[1,2,4,8] # Is 8>1? Is 8>2? Is 8>4? (have we finished looping? Put it at the end)
sorted = [1,2,4,5,8] # Is 5>1? Is 5>2? Is 5>4? Is 5>8? (No! Put it in the current index)
'''
def vicSort(array):
if len(array) == 0:
return array # if no items in array, return it! Don't waste my time!
sorted_arr = [] # Newly sorted array
## Place items as appropriate
def place(item):
for i,sarr in enumerate(sorted_arr):
if item > sarr and i == len(sorted_arr) - 1:
sorted_arr.append(item)
break
elif item < sarr:
sorted_arr.insert(i, item)
break
elif item > sarr and i != len(sorted_arr) - 1:
continue
## Perform the sort
def sort(item):
if len(sorted_arr) == 0:
sorted_arr.append(item)
else:
place(item)
## loop through each arr and sort
for arr in array:
sort(arr)
return sorted_arr
### Sorting numbers
unsorted_no = [2, 4, 1, 8, 5]
sorted_no = vicSort(unsorted_no)
print('Unsorted no: ', unsorted_no)
print('Sorted no: ', sorted_no)
print()
### Sorting strings or chars
unsorted_string = ['V', 'I', 'C', 'T', 'O', 'R']
sorted_string = vicSort(unsorted_string)
print('Unsorted arr: ', unsorted_string)
print('Sorted arr: ', sorted_string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment