From 971331b5ef850704242c21065cb0c41cf88b73d3 Mon Sep 17 00:00:00 2001 From: Ramvelivela Date: Thu, 24 Sep 2026 12:24:56 +0530 Subject: [PATCH] Make bitonic sort support comparable items --- sorts/bitonic_sort.py | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/sorts/bitonic_sort.py b/sorts/bitonic_sort.py index 600f8139603a..faafac12d28e 100644 --- a/sorts/bitonic_sort.py +++ b/sorts/bitonic_sort.py @@ -6,8 +6,14 @@ from __future__ import annotations +from typing import Protocol -def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None: + +class Comparable(Protocol): + def __lt__(self, other: object, /) -> bool: ... + + +def comp_and_swap[T: Coparable](array: list[T], index1: int, index2: int, direction: int) -> None: """Compare the value at given index1 and index2 of the array and swap them as per the given direction. @@ -38,7 +44,7 @@ def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> array[index1], array[index2] = array[index2], array[index1] -def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None: +def bitonic_merge[T: Comparable](array: list[T], low: int, length: int, direction: int) -> None: """ It recursively sorts a bitonic sequence in ascending order, if direction = 1, and in descending if direction = 0. @@ -62,7 +68,7 @@ def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> No bitonic_merge(array, low + middle, middle, direction) -def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None: +def bitonic_sort[T: Comparable](array: list[T], low: int, length: int, direction: int) -> None: """ This function first produces a bitonic sequence by recursively sorting its two halves in opposite sorting orders, and then calls bitonic_merge to make them in the @@ -76,6 +82,22 @@ def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> Non >>> bitonic_sort(arr, 0, 8, 0) >>> arr [145, 92, 34, 12, 0, -23, -121, -167] + + >>> arr = ["banana", "apple", "cherry","date"] + >>> bitonic_sort(arr, 0, 4, 1) + >>> arr + ['apple', 'banana', 'cherry', 'date'] + + >>> arr = [3, 1.5, 2, 4.5] + >>> bitonic_sort(arr, 0, 4, 1) + >>> arr + [1.5, 2, 3, 4.5] + + >>> arr = [1, "two", 3, "four"] + >>> bitonic_sort(arr, 0, 4, 1) + Traceback (most recent call last): + ... + TypeError: '>' not supported between instances of 'int' and 'str' """ if length > 1: middle = int(length / 2)