Last active
October 8, 2021 21:20
-
-
Save Grabber/e3016ed80b6a02c9cfce099c26e54ec8 to your computer and use it in GitHub Desktop.
I can't believe it can sort: is this the simplest (and most surprising) sorting algorithm ever?
This file contains 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
import random | |
def icantbelieveitcansort(a: list) -> tuple: | |
ops = 0 | |
for i in range(0, len(a)): | |
for j in range(0, len(a)): | |
if a[i] < a[j]: | |
a[i], a[j] = a[j], a[i] | |
ops += 1 | |
return (a, ops) | |
def exchangesort(a: list) -> tuple: | |
ops = 0 | |
for i in range(1, len(a)): | |
for j in range(0, i-1): | |
if a[i] < a[j]: | |
a[i], a[j] = a[j], a[i] | |
ops += 1 | |
return (a, ops) | |
if __name__ == "__main__": | |
print(icantbelieveitcansort([random.randrange(1, 50, 1) for i in range(1000)])) | |
print( exchangesort([random.randrange(1, 50, 1) for i in range(1000)])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(base) lvmc@Luizs-MacBook-Pro Desktop % python3 sorting.py
iteration efficiency for sorting 1000 numbers:
exchangesort
/icantbelieveicansort
= 498501 / 1000000 = 0,498501