sorts: make bogo_sort generic for comparable items (#15401)

* sorts: make bogo_sort generic for comparable items

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update tests/test_sorts.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
peeyushtiwary27
2026-09-22 19:06:45 +02:00
committed by GitHub
co-authored by pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Christian Clauss
parent 42c4c739af
commit e278aed789
2 changed files with 25 additions and 3 deletions
+16 -3
View File
@@ -14,9 +14,14 @@ python bogo_sort.py
"""
import random
from typing import Protocol
def bogo_sort(collection: list) -> list:
class Comparable(Protocol):
def __lt__(self, other: object, /) -> bool: ...
def bogo_sort[T: Comparable](collection: list[T]) -> list[T]:
"""Pure implementation of the bogosort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
@@ -28,11 +33,19 @@ def bogo_sort(collection: list) -> list:
[]
>>> bogo_sort([-2, -5, -45])
[-45, -5, -2]
>>> bogo_sort(["c", "a", "b"])
['a', 'b', 'c']
>>> bogo_sort([2.5, -1.0, 0.0])
[-1.0, 0.0, 2.5]
>>> bogo_sort([1, "a"])
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
"""
def is_sorted(collection: list) -> bool:
def is_sorted[T: Comparable](collection: list[T]) -> bool:
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
if collection[i + 1] < collection[i]:
return False
return True
+9
View File
@@ -23,6 +23,7 @@ from typing import NamedTuple
import pytest
from sorts.binary_insertion_sort import binary_insertion_sort
from sorts.bogo_sort import bogo_sort
from sorts.bubble_sort import bubble_sort_iterative, bubble_sort_recursive
from sorts.circle_sort import circle_sort
from sorts.cocktail_shaker_sort import cocktail_shaker_sort
@@ -154,3 +155,11 @@ def test_sort_rejects_non_comparable_items(sort) -> None:
def test_rec_insertion_sort_rejects_non_comparable_items() -> None:
with pytest.raises(TypeError):
rec_insertion_sort([1, "a"], 2)
def test_bogo_sort_comparable_items() -> None:
assert bogo_sort(["c", "a", "b"]) == ["a", "b", "c"]
assert bogo_sort([2.5, -1.0, 0.0]) == [-1.0, 0.0, 2.5]
with pytest.raises(TypeError):
bogo_sort([1, "a"])