Skip to content

Instantly share code, notes, and snippets.

@nocturn9x
Created June 10, 2022 09:53
Show Gist options
  • Save nocturn9x/3503a3d7f393ce4447b0e7cb80a45631 to your computer and use it in GitHub Desktop.
Save nocturn9x/3503a3d7f393ce4447b0e7cb80a45631 to your computer and use it in GitHub Desktop.
I was bored, so I optimized bubble sort to run around ~2/2.5x faster
from typing import List, TypeVar, Optional
from operator import gt, lt
T = TypeVar("T") # type: ignore
def is_sorted(l: List[T], *, reversed: Optional[bool] = False) -> bool:
if reversed:
op = gt
else:
op = lt
return all(op(l[i], l[i + 1]) for i in range(0, len(l) - 1))
def swap(l: List[T], a: int, b: int):
l[a], l[b] = l[b], l[a]
def naive_bubble_sort(l: List[T], *, reversed: Optional[bool] = False):
if reversed:
op = gt
else:
op = lt
for i in range(len(l)):
for j in range(len(l)):
if op(l[i], l[j]):
swap(l, i, j)
def smart_bubble_sort(l: List[T], *, reversed: Optional[bool] = False):
if reversed:
op = lt
else:
op = gt
current = 0
while current < len(l) - 1:
for j in range(current, len(l)):
if op(l[current], l[j]):
swap(l, current, j)
current += 1
if __name__ == "__main__":
import timeit
setup = "import random; l = list(range(100)); random.shuffle(l)"
print(timeit.timeit(setup=setup, stmt="naive_bubble_sort(l)", globals=globals(), number=10000))
print(timeit.timeit(setup=setup, stmt="smart_bubble_sort(l)", globals=globals(), number=10000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment