Skip to content

Instantly share code, notes, and snippets.

@himmelmaus
Created March 25, 2019 01:20
Show Gist options
  • Save himmelmaus/4a83d2077fc6e55ed288c592593dbfa9 to your computer and use it in GitHub Desktop.
Save himmelmaus/4a83d2077fc6e55ed288c592593dbfa9 to your computer and use it in GitHub Desktop.
A quick implementation of the thanos sort algorithm, removing half of the array's elements at a time until the array is sorted
from random import randint
def thanos_sort(array):
while not is_sorted(array):
target_length = int(len(array)/2)
while len(array) > target_length:
del array[randint(0, len(array)-1)]
return array
def is_sorted(array):
for i in range(len(array)-1):
if array[i] > array[i+1]:
return False
return True
@b10011
Copy link

b10011 commented Mar 25, 2019

int(len(array)/2) == len(array) // 2

@DenisVerkhoturov
Copy link

DenisVerkhoturov commented Mar 25, 2019

In Russia we usually use "stalin sort", it traverses a list and removes all the elements that break the order...

@BlueRaja
Copy link

BlueRaja commented Mar 25, 2019

This is O(n^2 log n) because deleting an arbitrary element from an array is an O(n) operation.

It can easily be done in O(n log n) by choosing n/2 random elements and copying them all to a new array at once.

@blake663
Copy link

blake663 commented Jul 13, 2020

This is O(n^2 log n) because deleting an arbitrary element from an array is an O(n) operation.

It can easily be done in O(n log n) by choosing n/2 random elements and copying them all to a new array at once.

I think the original would be O(n^2). Is that what you meant?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment