diff --git a/DIRECTORY.md b/DIRECTORY.md index 150e4e61ea06..38a7df0737e5 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -986,6 +986,7 @@ * [Doppler Frequency](physics/doppler_frequency.py) * [Escape Velocity](physics/escape_velocity.py) * [Grahams Law](physics/grahams_law.py) + * [Hamiltonian](physics/hamiltonian.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Hubble Parameter](physics/hubble_parameter.py) * [Ideal Gas Law](physics/ideal_gas_law.py) @@ -1404,6 +1405,7 @@ * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) + * [Sleep Sort](sorts/sleep_sort.py) * [Slowsort](sorts/slowsort.py) * [Smoothsort](sorts/smoothsort.py) * [Stalin Sort](sorts/stalin_sort.py) diff --git a/sorts/sleep_sort.py b/sorts/sleep_sort.py new file mode 100644 index 000000000000..cf38a3e017c0 --- /dev/null +++ b/sorts/sleep_sort.py @@ -0,0 +1,40 @@ +import threading +import time + + +def sleep_sort(arr): + """ + Sorts a list of positive integers using Sleep Sort. + + Args: + arr (list[int]): List of positive integers to sort. + + Returns: + list[int]: Sorted list in ascending order. + """ + result = [] + + def sleeper(x): + # Sleep for a duration proportional to the number + time.sleep(x * 0.01) # scale down to avoid long delays + result.append(x) + + threads = [threading.Thread(target=sleeper, args=(num,)) for num in arr] + + # Start all threads + for t in threads: + t.start() + + # Wait for all threads to finish + for t in threads: + t.join() + + return result + + +# Example Usage +if __name__ == "__main__": + numbers = [4, 1, 3, 2] + sorted_numbers = sleep_sort(numbers) + print("Original:", numbers) + print("Sorted:", sorted_numbers)