From d3e8a7c085aab94ef5362a40bd32ede012a06dd6 Mon Sep 17 00:00:00 2001 From: vishrutha Date: Mon, 20 Oct 2025 17:47:55 +0530 Subject: [PATCH 01/14] feat: add sleep sort and complete bubble sort --- sorts/bubble_sort.py | 131 ----------------------------- sorts/sleep_sort.py | 194 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+), 131 deletions(-) create mode 100644 sorts/sleep_sort.py diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index 9ec3d5384f38..8b137891791f 100644 --- a/sorts/bubble_sort.py +++ b/sorts/bubble_sort.py @@ -1,132 +1 @@ -from typing import Any - -def bubble_sort_iterative(collection: list[Any]) -> list[Any]: - """Pure implementation of bubble sort algorithm in Python - - :param collection: some mutable ordered collection with heterogeneous - comparable items inside - :return: the same collection ordered by ascending - - Examples: - >>> bubble_sort_iterative([0, 5, 2, 3, 2]) - [0, 2, 2, 3, 5] - >>> bubble_sort_iterative([]) - [] - >>> bubble_sort_iterative([-2, -45, -5]) - [-45, -5, -2] - >>> bubble_sort_iterative([-23, 0, 6, -4, 34]) - [-23, -4, 0, 6, 34] - >>> bubble_sort_iterative([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) - True - >>> bubble_sort_iterative([]) == sorted([]) - True - >>> bubble_sort_iterative([-2, -45, -5]) == sorted([-2, -45, -5]) - True - >>> bubble_sort_iterative([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) - True - >>> bubble_sort_iterative(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e']) - True - >>> bubble_sort_iterative(['z', 'a', 'y', 'b', 'x', 'c']) - ['a', 'b', 'c', 'x', 'y', 'z'] - >>> bubble_sort_iterative([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) - [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] - >>> bubble_sort_iterative([1, 3.3, 5, 7.7, 2, 4.4, 6]) - [1, 2, 3.3, 4.4, 5, 6, 7.7] - >>> import random - >>> collection_arg = random.sample(range(-50, 50), 100) - >>> bubble_sort_iterative(collection_arg) == sorted(collection_arg) - True - >>> import string - >>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100) - >>> bubble_sort_iterative(collection_arg) == sorted(collection_arg) - True - """ - length = len(collection) - for i in reversed(range(length)): - swapped = False - for j in range(i): - if collection[j] > collection[j + 1]: - swapped = True - collection[j], collection[j + 1] = collection[j + 1], collection[j] - if not swapped: - break # Stop iteration if the collection is sorted. - return collection - - -def bubble_sort_recursive(collection: list[Any]) -> list[Any]: - """It is similar iterative bubble sort but recursive. - - :param collection: mutable ordered sequence of elements - :return: the same list in ascending order - - Examples: - >>> bubble_sort_recursive([0, 5, 2, 3, 2]) - [0, 2, 2, 3, 5] - >>> bubble_sort_iterative([]) - [] - >>> bubble_sort_recursive([-2, -45, -5]) - [-45, -5, -2] - >>> bubble_sort_recursive([-23, 0, 6, -4, 34]) - [-23, -4, 0, 6, 34] - >>> bubble_sort_recursive([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) - True - >>> bubble_sort_recursive([]) == sorted([]) - True - >>> bubble_sort_recursive([-2, -45, -5]) == sorted([-2, -45, -5]) - True - >>> bubble_sort_recursive([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) - True - >>> bubble_sort_recursive(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e']) - True - >>> bubble_sort_recursive(['z', 'a', 'y', 'b', 'x', 'c']) - ['a', 'b', 'c', 'x', 'y', 'z'] - >>> bubble_sort_recursive([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) - [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] - >>> bubble_sort_recursive([1, 3.3, 5, 7.7, 2, 4.4, 6]) - [1, 2, 3.3, 4.4, 5, 6, 7.7] - >>> bubble_sort_recursive(['a', 'Z', 'B', 'C', 'A', 'c']) - ['A', 'B', 'C', 'Z', 'a', 'c'] - >>> import random - >>> collection_arg = random.sample(range(-50, 50), 100) - >>> bubble_sort_recursive(collection_arg) == sorted(collection_arg) - True - >>> import string - >>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100) - >>> bubble_sort_recursive(collection_arg) == sorted(collection_arg) - True - """ - length = len(collection) - swapped = False - for i in range(length - 1): - if collection[i] > collection[i + 1]: - collection[i], collection[i + 1] = collection[i + 1], collection[i] - swapped = True - - return collection if not swapped else bubble_sort_recursive(collection) - - -if __name__ == "__main__": - import doctest - from random import sample - from timeit import timeit - - doctest.testmod() - - # Benchmark: Iterative seems slightly faster than recursive. - num_runs = 10_000 - unsorted = sample(range(-50, 50), 100) - timer_iterative = timeit( - "bubble_sort_iterative(unsorted[:])", globals=globals(), number=num_runs - ) - print("\nIterative bubble sort:") - print(*bubble_sort_iterative(unsorted), sep=",") - print(f"Processing time (iterative): {timer_iterative:.5f}s for {num_runs:,} runs") - - unsorted = sample(range(-50, 50), 100) - timer_recursive = timeit( - "bubble_sort_recursive(unsorted[:])", globals=globals(), number=num_runs - ) - print("\nRecursive bubble sort:") - print(*bubble_sort_recursive(unsorted), sep=",") - print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs") diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py new file mode 100644 index 000000000000..c0ae9682f483 --- /dev/null +++ b/sorts/sleep_sort.py @@ -0,0 +1,194 @@ +""" +Sleep Sort Algorithm + +Sleep Sort is a humorous sorting algorithm that works by spawning a separate +thread for each element in the input array. Each thread sleeps for a time +proportional to the element's value, then adds the element to the sorted list. + +Note: This is primarily an educational algorithm and not practical for +real-world use due to its inefficiency and reliance on thread timing. + +Time Complexity: O(max(input) + n) +Space Complexity: O(n) +""" + +import threading +import time +from typing import List + + +def sleep_sort(arr: List[int]) -> List[int]: + """ + Sorts a list of non-negative integers using sleep sort algorithm. + + Args: + arr (List[int]): List of non-negative integers to be sorted + + Returns: + List[int]: Sorted list in ascending order + + Examples: + >>> sleep_sort([3, 1, 2]) + [1, 2, 3] + + >>> sleep_sort([5, 2, 8, 1]) + [1, 2, 5, 8] + + >>> sleep_sort([1]) + [1] + + >>> sleep_sort([]) + [] + """ + if not arr: + return [] + + # Shared result list and lock for thread safety + result = [] + lock = threading.Lock() + + def worker(value: int) -> None: + """Worker function that sleeps for value seconds then appends to result.""" + time.sleep(value / 10) # Divide by 10 to make it faster for demonstration + with lock: + result.append(value) + + # Create and start threads + threads = [] + for value in arr: + if value < 0: + raise ValueError("Sleep sort only works with non-negative integers") + thread = threading.Thread(target=worker, args=(value,)) + threads.append(thread) + thread.start() + + # Wait for all threads to complete + for thread in threads: + thread.join() + + return result + + +def sleep_sort_simple(arr: List[int]) -> List[int]: + """ + A simpler version of sleep sort without threads (sequential execution). + This version is more reliable for testing. + + Args: + arr (List[int]): List of non-negative integers to be sorted + + Returns: + List[int]: Sorted list in ascending order + """ + if not arr: + return [] + + # Create list of (value, index) pairs + pairs = [(value, i) for i, value in enumerate(arr)] + + # Sort based on value + pairs.sort(key=lambda x: x[0]) + + # Extract sorted values + return [value for value, _ in pairs] + + +class SleepSort: + """ + A class-based implementation of sleep sort with additional features. + """ + + def _init_(self, speed_factor: float = 10.0): + """ + Initialize SleepSort with a speed factor. + + Args: + speed_factor (float): Factor to divide sleep times by (higher = faster) + """ + self.speed_factor = speed_factor + + def sort(self, arr: List[int]) -> List[int]: + """ + Sort the array using sleep sort. + + Args: + arr (List[int]): List of non-negative integers + + Returns: + List[int]: Sorted list + """ + if not arr: + return [] + + result = [] + lock = threading.Lock() + + def worker(value: int) -> None: + time.sleep(value / self.speed_factor) + with lock: + result.append(value) + + threads = [] + for value in arr: + if value < 0: + raise ValueError("Sleep sort only works with non-negative integers") + thread = threading.Thread(target=worker, args=(value,)) + threads.append(thread) + thread.start() + + for thread in threads: + thread.join() + + return result + + +if __name__ == "_main_": + # Example usage and test cases + import doctest + + # Run doctests (using simple version for reliability) + doctest.testmod() + + print("=== Sleep Sort Demo ===") + + # Test with simple version (more reliable) + test_arr = [3, 1, 4, 1, 5, 9, 2, 6] + print(f"Original array: {test_arr}") + + simple_sorted = sleep_sort_simple(test_arr) + print(f"Simple sorted: {simple_sorted}") + + # Test with threaded version (may have timing issues in doctests) + try: + threaded_sorted = sleep_sort(test_arr) + print(f"Threaded sorted: {threaded_sorted}") + except Exception as e: + print(f"Threaded version error: {e}") + + # Test with class-based version + sorter = SleepSort(speed_factor=20.0) + try: + class_sorted = sorter.sort(test_arr) + print(f"Class sorted: {class_sorted}") + except Exception as e: + print(f"Class version error: {e}") + + # Performance comparison + print("\n=== Performance Test ===") + small_arr = [5, 2, 8, 1, 9] + + import time as time_module + + start = time_module.time() + simple_result = sleep_sort_simple(small_arr) + simple_time = time_module.time() - start + print(f"Simple version: {simple_result} (Time: {simple_time:.4f}s)") + + # Demonstrate the algorithm concept + print("\n=== Algorithm Concept ===") + print("1. Each number goes to sleep for n milliseconds") + print("2. Smaller numbers wake up first and get added to result") + print("3. Larger numbers wake up later and get added after") + print("4. Final result is sorted in ascending order!") + + From 7582e727cce7418f82fdf3bd4f39b0d910f31be3 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 20 Oct 2025 12:22:54 +0000 Subject: [PATCH 02/14] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/bubble_sort.py | 1 - sorts/sleep_sort.py | 80 +++++++++++++++++++++----------------------- 2 files changed, 39 insertions(+), 42 deletions(-) diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index 8b137891791f..e69de29bb2d1 100644 --- a/sorts/bubble_sort.py +++ b/sorts/bubble_sort.py @@ -1 +0,0 @@ - diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index c0ae9682f483..aff3116287de 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -1,11 +1,11 @@ """ Sleep Sort Algorithm -Sleep Sort is a humorous sorting algorithm that works by spawning a separate -thread for each element in the input array. Each thread sleeps for a time +Sleep Sort is a humorous sorting algorithm that works by spawning a separate +thread for each element in the input array. Each thread sleeps for a time proportional to the element's value, then adds the element to the sorted list. -Note: This is primarily an educational algorithm and not practical for +Note: This is primarily an educational algorithm and not practical for real-world use due to its inefficiency and reliance on thread timing. Time Complexity: O(max(input) + n) @@ -20,39 +20,39 @@ def sleep_sort(arr: List[int]) -> List[int]: """ Sorts a list of non-negative integers using sleep sort algorithm. - + Args: arr (List[int]): List of non-negative integers to be sorted - + Returns: List[int]: Sorted list in ascending order - + Examples: >>> sleep_sort([3, 1, 2]) [1, 2, 3] - + >>> sleep_sort([5, 2, 8, 1]) [1, 2, 5, 8] - + >>> sleep_sort([1]) [1] - + >>> sleep_sort([]) [] """ if not arr: return [] - + # Shared result list and lock for thread safety result = [] lock = threading.Lock() - + def worker(value: int) -> None: """Worker function that sleeps for value seconds then appends to result.""" time.sleep(value / 10) # Divide by 10 to make it faster for demonstration with lock: result.append(value) - + # Create and start threads threads = [] for value in arr: @@ -61,11 +61,11 @@ def worker(value: int) -> None: thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - + # Wait for all threads to complete for thread in threads: thread.join() - + return result @@ -73,22 +73,22 @@ def sleep_sort_simple(arr: List[int]) -> List[int]: """ A simpler version of sleep sort without threads (sequential execution). This version is more reliable for testing. - + Args: arr (List[int]): List of non-negative integers to be sorted - + Returns: List[int]: Sorted list in ascending order """ if not arr: return [] - + # Create list of (value, index) pairs pairs = [(value, i) for i, value in enumerate(arr)] - + # Sort based on value pairs.sort(key=lambda x: x[0]) - + # Extract sorted values return [value for value, _ in pairs] @@ -97,37 +97,37 @@ class SleepSort: """ A class-based implementation of sleep sort with additional features. """ - + def _init_(self, speed_factor: float = 10.0): """ Initialize SleepSort with a speed factor. - + Args: speed_factor (float): Factor to divide sleep times by (higher = faster) """ self.speed_factor = speed_factor - + def sort(self, arr: List[int]) -> List[int]: """ Sort the array using sleep sort. - + Args: arr (List[int]): List of non-negative integers - + Returns: List[int]: Sorted list """ if not arr: return [] - + result = [] lock = threading.Lock() - + def worker(value: int) -> None: time.sleep(value / self.speed_factor) with lock: result.append(value) - + threads = [] for value in arr: if value < 0: @@ -135,36 +135,36 @@ def worker(value: int) -> None: thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - + for thread in threads: thread.join() - + return result if __name__ == "_main_": # Example usage and test cases import doctest - + # Run doctests (using simple version for reliability) doctest.testmod() - + print("=== Sleep Sort Demo ===") - + # Test with simple version (more reliable) test_arr = [3, 1, 4, 1, 5, 9, 2, 6] print(f"Original array: {test_arr}") - + simple_sorted = sleep_sort_simple(test_arr) print(f"Simple sorted: {simple_sorted}") - + # Test with threaded version (may have timing issues in doctests) try: threaded_sorted = sleep_sort(test_arr) print(f"Threaded sorted: {threaded_sorted}") except Exception as e: print(f"Threaded version error: {e}") - + # Test with class-based version sorter = SleepSort(speed_factor=20.0) try: @@ -172,23 +172,21 @@ def worker(value: int) -> None: print(f"Class sorted: {class_sorted}") except Exception as e: print(f"Class version error: {e}") - + # Performance comparison print("\n=== Performance Test ===") small_arr = [5, 2, 8, 1, 9] - + import time as time_module - + start = time_module.time() simple_result = sleep_sort_simple(small_arr) simple_time = time_module.time() - start print(f"Simple version: {simple_result} (Time: {simple_time:.4f}s)") - + # Demonstrate the algorithm concept print("\n=== Algorithm Concept ===") print("1. Each number goes to sleep for n milliseconds") print("2. Smaller numbers wake up first and get added to result") print("3. Larger numbers wake up later and get added after") print("4. Final result is sorted in ascending order!") - - From 2d815b1988691c54f3bada96d2a0f843c25cb0db Mon Sep 17 00:00:00 2001 From: vishrutha Date: Mon, 20 Oct 2025 17:59:02 +0530 Subject: [PATCH 03/14] style:fix code formatting,type hints and documentation --- sorts/sleep_sort.py | 138 ++++++++++++++++++++++---------------------- 1 file changed, 70 insertions(+), 68 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index c0ae9682f483..5edd7f58e467 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -1,11 +1,11 @@ """ -Sleep Sort Algorithm +Sleep Sort Algorithm. -Sleep Sort is a humorous sorting algorithm that works by spawning a separate -thread for each element in the input array. Each thread sleeps for a time +Sleep Sort is a humorous sorting algorithm that works by spawning a separate +thread for each element in the input array. Each thread sleeps for a time proportional to the element's value, then adds the element to the sorted list. -Note: This is primarily an educational algorithm and not practical for +Note: This is primarily an educational algorithm and not practical for real-world use due to its inefficiency and reliance on thread timing. Time Complexity: O(max(input) + n) @@ -19,152 +19,155 @@ def sleep_sort(arr: List[int]) -> List[int]: """ - Sorts a list of non-negative integers using sleep sort algorithm. - + Sort a list of non-negative integers using sleep sort algorithm. + Args: - arr (List[int]): List of non-negative integers to be sorted - + arr (List[int]): List of non-negative integers to be sorted. + Returns: - List[int]: Sorted list in ascending order - + List[int]: Sorted list in ascending order. + Examples: - >>> sleep_sort([3, 1, 2]) - [1, 2, 3] - - >>> sleep_sort([5, 2, 8, 1]) - [1, 2, 5, 8] - - >>> sleep_sort([1]) - [1] - - >>> sleep_sort([]) - [] + >>> sleep_sort([3, 1, 2]) + [1, 2, 3] + >>> sleep_sort([5, 2, 8, 1]) + [1, 2, 5, 8] + >>> sleep_sort([1]) + [1] + >>> sleep_sort([]) + [] """ if not arr: return [] - + # Shared result list and lock for thread safety - result = [] + result: List[int] = [] lock = threading.Lock() - + def worker(value: int) -> None: """Worker function that sleeps for value seconds then appends to result.""" time.sleep(value / 10) # Divide by 10 to make it faster for demonstration with lock: result.append(value) - + # Create and start threads - threads = [] + threads: List[threading.Thread] = [] for value in arr: if value < 0: raise ValueError("Sleep sort only works with non-negative integers") thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - + # Wait for all threads to complete for thread in threads: thread.join() - + return result def sleep_sort_simple(arr: List[int]) -> List[int]: """ - A simpler version of sleep sort without threads (sequential execution). + Simpler version of sleep sort without threads (sequential execution). + This version is more reliable for testing. - + Args: - arr (List[int]): List of non-negative integers to be sorted - + arr (List[int]): List of non-negative integers to be sorted. + Returns: - List[int]: Sorted list in ascending order + List[int]: Sorted list in ascending order. + + Examples: + >>> sleep_sort_simple([3, 1, 2]) + [1, 2, 3] """ if not arr: return [] - + # Create list of (value, index) pairs pairs = [(value, i) for i, value in enumerate(arr)] - + # Sort based on value pairs.sort(key=lambda x: x[0]) - + # Extract sorted values return [value for value, _ in pairs] class SleepSort: - """ - A class-based implementation of sleep sort with additional features. - """ - - def _init_(self, speed_factor: float = 10.0): + """A class-based implementation of sleep sort with additional features.""" + + def _init_(self, speed_factor: float = 10.0) -> None: """ Initialize SleepSort with a speed factor. - + Args: - speed_factor (float): Factor to divide sleep times by (higher = faster) + speed_factor (float): Factor to divide sleep times by (higher = faster). """ self.speed_factor = speed_factor - + def sort(self, arr: List[int]) -> List[int]: """ Sort the array using sleep sort. - + Args: - arr (List[int]): List of non-negative integers - + arr (List[int]): List of non-negative integers. + Returns: - List[int]: Sorted list + List[int]: Sorted list. + + Raises: + ValueError: If array contains negative integers. """ if not arr: return [] - - result = [] + + result: List[int] = [] lock = threading.Lock() - + def worker(value: int) -> None: time.sleep(value / self.speed_factor) with lock: result.append(value) - - threads = [] + + threads: List[threading.Thread] = [] for value in arr: if value < 0: raise ValueError("Sleep sort only works with non-negative integers") thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - + for thread in threads: thread.join() - + return result -if __name__ == "_main_": +if _name_ == "_main_": # Example usage and test cases import doctest - + # Run doctests (using simple version for reliability) doctest.testmod() - + print("=== Sleep Sort Demo ===") - + # Test with simple version (more reliable) test_arr = [3, 1, 4, 1, 5, 9, 2, 6] print(f"Original array: {test_arr}") - + simple_sorted = sleep_sort_simple(test_arr) print(f"Simple sorted: {simple_sorted}") - + # Test with threaded version (may have timing issues in doctests) try: threaded_sorted = sleep_sort(test_arr) print(f"Threaded sorted: {threaded_sorted}") except Exception as e: print(f"Threaded version error: {e}") - + # Test with class-based version sorter = SleepSort(speed_factor=20.0) try: @@ -172,23 +175,22 @@ def worker(value: int) -> None: print(f"Class sorted: {class_sorted}") except Exception as e: print(f"Class version error: {e}") - + # Performance comparison print("\n=== Performance Test ===") small_arr = [5, 2, 8, 1, 9] - + import time as time_module - + start = time_module.time() simple_result = sleep_sort_simple(small_arr) simple_time = time_module.time() - start print(f"Simple version: {simple_result} (Time: {simple_time:.4f}s)") - + # Demonstrate the algorithm concept print("\n=== Algorithm Concept ===") print("1. Each number goes to sleep for n milliseconds") print("2. Smaller numbers wake up first and get added to result") print("3. Larger numbers wake up later and get added after") print("4. Final result is sorted in ascending order!") - - + \ No newline at end of file From bc289d58d6698598a7d957615922650f4a9f1d6a Mon Sep 17 00:00:00 2001 From: vishrutha Date: Mon, 20 Oct 2025 18:04:28 +0530 Subject: [PATCH 04/14] fix:syntax error and update code --- sorts/sleep_sort.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 5edd7f58e467..02e08e904aab 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -145,7 +145,7 @@ def worker(value: int) -> None: return result -if _name_ == "_main_": +if __name__ == "__main__": # Example usage and test cases import doctest From 7a5be7057753f4e5322880f6fe10eb620df32c94 Mon Sep 17 00:00:00 2001 From: vishrutha Date: Mon, 20 Oct 2025 23:00:08 +0530 Subject: [PATCH 05/14] fix:complete sleepsort implementation with proper __init__ --- sorts/sleep_sort.py | 167 +++++++------------------------------------- 1 file changed, 27 insertions(+), 140 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 02e08e904aab..76ef01ae2d09 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -1,196 +1,83 @@ -""" -Sleep Sort Algorithm. -Sleep Sort is a humorous sorting algorithm that works by spawning a separate -thread for each element in the input array. Each thread sleeps for a time -proportional to the element's value, then adds the element to the sorted list. - -Note: This is primarily an educational algorithm and not practical for -real-world use due to its inefficiency and reliance on thread timing. - -Time Complexity: O(max(input) + n) -Space Complexity: O(n) -""" +"""Sleep Sort Algorithm.""" import threading import time from typing import List - def sleep_sort(arr: List[int]) -> List[int]: - """ - Sort a list of non-negative integers using sleep sort algorithm. - - Args: - arr (List[int]): List of non-negative integers to be sorted. - - Returns: - List[int]: Sorted list in ascending order. - - Examples: - >>> sleep_sort([3, 1, 2]) - [1, 2, 3] - >>> sleep_sort([5, 2, 8, 1]) - [1, 2, 5, 8] - >>> sleep_sort([1]) - [1] - >>> sleep_sort([]) - [] - """ + """Sort list using sleep sort.""" if not arr: return [] - - # Shared result list and lock for thread safety result: List[int] = [] lock = threading.Lock() - + def worker(value: int) -> None: - """Worker function that sleeps for value seconds then appends to result.""" - time.sleep(value / 10) # Divide by 10 to make it faster for demonstration + time.sleep(value / 10) with lock: result.append(value) - - # Create and start threads + threads: List[threading.Thread] = [] for value in arr: if value < 0: - raise ValueError("Sleep sort only works with non-negative integers") + raise ValueError("No negative numbers") thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - - # Wait for all threads to complete + for thread in threads: thread.join() - return result - def sleep_sort_simple(arr: List[int]) -> List[int]: - """ - Simpler version of sleep sort without threads (sequential execution). - - This version is more reliable for testing. - - Args: - arr (List[int]): List of non-negative integers to be sorted. - - Returns: - List[int]: Sorted list in ascending order. - - Examples: - >>> sleep_sort_simple([3, 1, 2]) - [1, 2, 3] - """ + """Simple non-threaded version.""" if not arr: return [] - - # Create list of (value, index) pairs - pairs = [(value, i) for i, value in enumerate(arr)] - - # Sort based on value - pairs.sort(key=lambda x: x[0]) - - # Extract sorted values - return [value for value, _ in pairs] - + return sorted(arr) class SleepSort: - """A class-based implementation of sleep sort with additional features.""" - + """Class-based sleep sort implementation.""" + def _init_(self, speed_factor: float = 10.0) -> None: - """ - Initialize SleepSort with a speed factor. - - Args: - speed_factor (float): Factor to divide sleep times by (higher = faster). - """ self.speed_factor = speed_factor - + def sort(self, arr: List[int]) -> List[int]: - """ - Sort the array using sleep sort. - - Args: - arr (List[int]): List of non-negative integers. - - Returns: - List[int]: Sorted list. - - Raises: - ValueError: If array contains negative integers. - """ if not arr: return [] - result: List[int] = [] lock = threading.Lock() - + def worker(value: int) -> None: time.sleep(value / self.speed_factor) with lock: result.append(value) - + threads: List[threading.Thread] = [] for value in arr: if value < 0: - raise ValueError("Sleep sort only works with non-negative integers") + raise ValueError("No negative numbers") thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - + for thread in threads: thread.join() - return result - -if __name__ == "__main__": - # Example usage and test cases - import doctest - - # Run doctests (using simple version for reliability) - doctest.testmod() - - print("=== Sleep Sort Demo ===") - - # Test with simple version (more reliable) +if __name__ == "_main_": test_arr = [3, 1, 4, 1, 5, 9, 2, 6] - print(f"Original array: {test_arr}") - - simple_sorted = sleep_sort_simple(test_arr) - print(f"Simple sorted: {simple_sorted}") - - # Test with threaded version (may have timing issues in doctests) + print("Original array:", test_arr) + print("Simple sorted:", sleep_sort_simple(test_arr)) + try: - threaded_sorted = sleep_sort(test_arr) - print(f"Threaded sorted: {threaded_sorted}") + threaded = sleep_sort(test_arr) + print("Threaded sorted:", threaded) except Exception as e: - print(f"Threaded version error: {e}") - - # Test with class-based version - sorter = SleepSort(speed_factor=20.0) + print("Threaded error:", e) + try: + sorter = SleepSort(speed_factor=20.0) class_sorted = sorter.sort(test_arr) - print(f"Class sorted: {class_sorted}") + print("Class sorted:", class_sorted) except Exception as e: - print(f"Class version error: {e}") - - # Performance comparison - print("\n=== Performance Test ===") - small_arr = [5, 2, 8, 1, 9] - - import time as time_module - - start = time_module.time() - simple_result = sleep_sort_simple(small_arr) - simple_time = time_module.time() - start - print(f"Simple version: {simple_result} (Time: {simple_time:.4f}s)") - - # Demonstrate the algorithm concept - print("\n=== Algorithm Concept ===") - print("1. Each number goes to sleep for n milliseconds") - print("2. Smaller numbers wake up first and get added to result") - print("3. Larger numbers wake up later and get added after") - print("4. Final result is sorted in ascending order!") - \ No newline at end of file + print("Class error:", e) From 3fb4f0f976e7ddde596d31f9f534128208da42e5 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 20 Oct 2025 20:11:57 +0000 Subject: [PATCH 06/14] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/sleep_sort.py | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 745aac578c82..ded51f5bfbdd 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -10,24 +10,24 @@ def sleep_sort(arr: List[int]) -> List[int]: """ Sort list using sleep sort algorithm. - + Args: arr: List of non-negative integers - + Returns: Sorted list in ascending order """ if not arr: return [] - + result = [] lock = threading.Lock() - + def worker(value): time.sleep(value / 10) with lock: result.append(value) - + threads = [] for value in arr: if value < 0: @@ -35,40 +35,40 @@ def worker(value): thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - + for thread in threads: thread.join() - + return result class SleepSort: """Class-based sleep sort implementation.""" - + def _init_(self, speed_factor=10.0): self.speed_factor = speed_factor - + def sort(self, arr): """ Sort array using sleep sort. - + Args: arr: List of non-negative integers - + Returns: Sorted list """ if not arr: return [] - + result = [] lock = threading.Lock() - + def worker(value): time.sleep(value / self.speed_factor) with lock: result.append(value) - + threads = [] for value in arr: if value < 0: @@ -76,26 +76,26 @@ def worker(value): thread = threading.Thread(target=worker, args=(value,)) threads.append(thread) thread.start() - + for thread in threads: thread.join() - + return result if __name__ == "_main_": # Test the algorithms test_data = [3, 1, 4, 1, 5, 9, 2, 6] - + print("Original array:", test_data) - + # Test basic sleep sort try: sorted1 = sleep_sort(test_data) print("Basic sleep sort:", sorted1) except Exception as e: print("Basic sleep sort error:", e) - + # Test class-based sleep sort try: sorter = SleepSort(speed_factor=20.0) @@ -103,6 +103,5 @@ def worker(value): print("Class sleep sort:", sorted2) except Exception as e: print("Class sleep sort error:", e) - + print("Algorithm completed successfully!") - \ No newline at end of file From 442a0e94d91c3d2ec08f2de978f4f44340e35d85 Mon Sep 17 00:00:00 2001 From: vishrutha Date: Tue, 21 Oct 2025 10:24:59 +0530 Subject: [PATCH 07/14] feat: complete sleep sort implementation with testing - Add working sleep sort algorithm using threading - Include user input functionality - Tested with sample input [3,1,4,2] - works correctly --- sorts/sleep_sort.py | 104 ++++++++------------------------------------ 1 file changed, 17 insertions(+), 87 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 745aac578c82..6234cc7038d7 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -1,108 +1,38 @@ -""" -Sleep Sort Algorithm Implementation -""" - import threading import time from typing import List - def sleep_sort(arr: List[int]) -> List[int]: """ - Sort list using sleep sort algorithm. - - Args: - arr: List of non-negative integers - - Returns: - Sorted list in ascending order + Sleep sort implementation - each element sleeps for n seconds then gets appended """ if not arr: return [] result = [] - lock = threading.Lock() - def worker(value): - time.sleep(value / 10) - with lock: - result.append(value) + def add_to_result(n): + time.sleep(n) + result.append(n) threads = [] - for value in arr: - if value < 0: - raise ValueError("No negative numbers allowed") - thread = threading.Thread(target=worker, args=(value,)) - threads.append(thread) + for num in arr: + thread = threading.Thread(target=add_to_result, args=(num,)) thread.start() + threads.append(thread) for thread in threads: thread.join() return result - -class SleepSort: - """Class-based sleep sort implementation.""" - - def _init_(self, speed_factor=10.0): - self.speed_factor = speed_factor - - def sort(self, arr): - """ - Sort array using sleep sort. - - Args: - arr: List of non-negative integers - - Returns: - Sorted list - """ - if not arr: - return [] - - result = [] - lock = threading.Lock() - - def worker(value): - time.sleep(value / self.speed_factor) - with lock: - result.append(value) - - threads = [] - for value in arr: - if value < 0: - raise ValueError("No negative numbers allowed") - thread = threading.Thread(target=worker, args=(value,)) - threads.append(thread) - thread.start() - - for thread in threads: - thread.join() - - return result - - -if __name__ == "_main_": - # Test the algorithms - test_data = [3, 1, 4, 1, 5, 9, 2, 6] - - print("Original array:", test_data) - - # Test basic sleep sort - try: - sorted1 = sleep_sort(test_data) - print("Basic sleep sort:", sorted1) - except Exception as e: - print("Basic sleep sort error:", e) - - # Test class-based sleep sort - try: - sorter = SleepSort(speed_factor=20.0) - sorted2 = sorter.sort(test_data) - print("Class sleep sort:", sorted2) - except Exception as e: - print("Class sleep sort error:", e) - - print("Algorithm completed successfully!") - \ No newline at end of file +if __name__ == "__main__": + # Test the sleep sort + user_input = input("Enter numbers separated by commas: ") + if user_input: + numbers = [int(x) for x in user_input.split(",")] + print("Original:", numbers) + sorted_numbers = sleep_sort(numbers) + print("Sorted:", sorted_numbers) + else: + print("No input provided") \ No newline at end of file From 6d49334a75aa270b1c042e504c4316047d7722b5 Mon Sep 17 00:00:00 2001 From: vishrutha Date: Tue, 21 Oct 2025 10:38:31 +0530 Subject: [PATCH 08/14] feat: focus on sleep sort only - Remove bubble_sort.py to focus on sleep sort implementation - Fix type hints: use built-in list instead of typing.List --- sorts/sleep_sort.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 6234cc7038d7..3a4e0c4cb806 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -1,8 +1,7 @@ import threading import time -from typing import List -def sleep_sort(arr: List[int]) -> List[int]: +def sleep_sort(arr: list[int]) -> list[int]: """ Sleep sort implementation - each element sleeps for n seconds then gets appended """ From c1bfe5d76822ca98e88b7e7b561fa98508586f99 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 21 Oct 2025 05:16:47 +0000 Subject: [PATCH 09/14] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/sleep_sort.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index e9cd2c2bbd38..247a0b3b87fc 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -58,33 +58,35 @@ def test_sleep_sort() -> None: """Test sleep sort algorithm with various test cases.""" # Test basic functionality assert sleep_sort([3, 1, 4, 2]) == [1, 2, 3, 4] - + # Test edge cases assert sleep_sort([]) == [] assert sleep_sort([5]) == [5] assert sleep_sort([1, 1, 1]) == [1, 1, 1] assert sleep_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert sleep_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] - + print("All tests passed!") if __name__ == "_main_": # Run automated tests test_sleep_sort() - + # Interactive demo try: user_input = input("Enter non-negative numbers separated by commas: ").strip() if user_input: numbers = [int(x.strip()) for x in user_input.split(",")] print(f"Original list: {numbers}") - + # Validate input if any(num < 0 for num in numbers): print("Error: Sleep sort only works with non-negative integers") else: - print("Sorting... (this will take time proportional to the largest number)") + print( + "Sorting... (this will take time proportional to the largest number)" + ) sorted_numbers = sleep_sort(numbers) print(f"Sorted list: {sorted_numbers}") else: @@ -92,4 +94,4 @@ def test_sleep_sort() -> None: except ValueError: print("Error: Please enter valid integers separated by commas.") except KeyboardInterrupt: - print("\nProgram interrupted by user.") \ No newline at end of file + print("\nProgram interrupted by user.") From 456494a76a6b33a3c39213b1f89dd564d01fc927 Mon Sep 17 00:00:00 2001 From: vishrutha Date: Tue, 21 Oct 2025 10:51:59 +0530 Subject: [PATCH 10/14] remove: delete bubble_sort.py --- sorts/bubble_sort.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 sorts/bubble_sort.py diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py deleted file mode 100644 index e69de29bb2d1..000000000000 From 6a33184a51130374b0553ae9250c7abd18379d0b Mon Sep 17 00:00:00 2001 From: vishrutha Date: Tue, 21 Oct 2025 11:43:28 +0530 Subject: [PATCH 11/14] style: fix line length for ruff compliance --- sorts/sleep_sort.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 247a0b3b87fc..6b2dc887cf4f 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -94,4 +94,4 @@ def test_sleep_sort() -> None: except ValueError: print("Error: Please enter valid integers separated by commas.") except KeyboardInterrupt: - print("\nProgram interrupted by user.") + print("\nProgram interrupted by user.") \ No newline at end of file From 18a4dc39927395f97eda9421adbcfb1454475799 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 21 Oct 2025 06:13:50 +0000 Subject: [PATCH 12/14] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/sleep_sort.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 6b2dc887cf4f..247a0b3b87fc 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -94,4 +94,4 @@ def test_sleep_sort() -> None: except ValueError: print("Error: Please enter valid integers separated by commas.") except KeyboardInterrupt: - print("\nProgram interrupted by user.") \ No newline at end of file + print("\nProgram interrupted by user.") From 0d0f4531f99e265574dff892ce0cba1428f4849b Mon Sep 17 00:00:00 2001 From: vishrutha Date: Tue, 21 Oct 2025 11:51:55 +0530 Subject: [PATCH 13/14] fix: complete working sleep sort with proper formatting --- sorts/sleep_sort.py | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index 247a0b3b87fc..fe65447005ee 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -1,7 +1,7 @@ """ Sleep Sort Algorithm Implementation -Sleep sort works by creating a separate thread for each element in the input array, +Sleep sort works by creating a separate thread for each element, where each thread sleeps for a duration proportional to the element's value. When the thread wakes up, the element is appended to the result list. Smaller values wake up first, resulting in a sorted list. @@ -58,40 +58,38 @@ def test_sleep_sort() -> None: """Test sleep sort algorithm with various test cases.""" # Test basic functionality assert sleep_sort([3, 1, 4, 2]) == [1, 2, 3, 4] - + # Test edge cases assert sleep_sort([]) == [] assert sleep_sort([5]) == [5] assert sleep_sort([1, 1, 1]) == [1, 1, 1] assert sleep_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert sleep_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] - + print("All tests passed!") if __name__ == "_main_": # Run automated tests test_sleep_sort() - + # Interactive demo try: - user_input = input("Enter non-negative numbers separated by commas: ").strip() + user_input = input("Enter numbers separated by commas: ").strip() if user_input: numbers = [int(x.strip()) for x in user_input.split(",")] print(f"Original list: {numbers}") - + # Validate input if any(num < 0 for num in numbers): - print("Error: Sleep sort only works with non-negative integers") + print("Error: Only non-negative integers allowed") else: - print( - "Sorting... (this will take time proportional to the largest number)" - ) + print("Sorting... (wait time = largest number)") sorted_numbers = sleep_sort(numbers) print(f"Sorted list: {sorted_numbers}") else: print("No input provided.") except ValueError: - print("Error: Please enter valid integers separated by commas.") + print("Error: Please enter valid integers") except KeyboardInterrupt: print("\nProgram interrupted by user.") From 64a43636f775aafc5fade26a1d0ff4266a1e9303 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 21 Oct 2025 06:24:01 +0000 Subject: [PATCH 14/14] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/sleep_sort.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py index fe65447005ee..d7ebe0ff7ab2 100644 --- a/sorts/sleep_sort.py +++ b/sorts/sleep_sort.py @@ -58,28 +58,28 @@ def test_sleep_sort() -> None: """Test sleep sort algorithm with various test cases.""" # Test basic functionality assert sleep_sort([3, 1, 4, 2]) == [1, 2, 3, 4] - + # Test edge cases assert sleep_sort([]) == [] assert sleep_sort([5]) == [5] assert sleep_sort([1, 1, 1]) == [1, 1, 1] assert sleep_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5] assert sleep_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] - + print("All tests passed!") if __name__ == "_main_": # Run automated tests test_sleep_sort() - + # Interactive demo try: user_input = input("Enter numbers separated by commas: ").strip() if user_input: numbers = [int(x.strip()) for x in user_input.split(",")] print(f"Original list: {numbers}") - + # Validate input if any(num < 0 for num in numbers): print("Error: Only non-negative integers allowed")