From 64b5672dba8c6b23844a2957e315e0403bf49800 Mon Sep 17 00:00:00 2001 From: Syed Syab Date: Fri, 5 Jan 2024 14:47:45 +0500 Subject: [PATCH] 2 Sorting Algorithms Added in Python --- algorithms/Python/sorting/bucket_sort.py | 22 ++++++++++++++ algorithms/Python/sorting/cycle_sort.py | 37 ++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 algorithms/Python/sorting/bucket_sort.py create mode 100644 algorithms/Python/sorting/cycle_sort.py diff --git a/algorithms/Python/sorting/bucket_sort.py b/algorithms/Python/sorting/bucket_sort.py new file mode 100644 index 000000000..03bc7c8ce --- /dev/null +++ b/algorithms/Python/sorting/bucket_sort.py @@ -0,0 +1,22 @@ +def bucket_sort(arr): + # Find the maximum value in the array + max_val = max(arr) + + # Create buckets + buckets = [[] for _ in range(max_val + 1)] + + # Place each element in its respective bucket + for num in arr: + buckets[num].append(num) + + # Concatenate the buckets to get the sorted array + sorted_arr = [] + for bucket in buckets: + sorted_arr.extend(bucket) + + return sorted_arr + +# Example: +arr = [5, 2, 9, 1, 5, 6] +sorted_arr = bucket_sort(arr) +print("Bucket Sort:", sorted_arr) diff --git a/algorithms/Python/sorting/cycle_sort.py b/algorithms/Python/sorting/cycle_sort.py new file mode 100644 index 000000000..86eeeff99 --- /dev/null +++ b/algorithms/Python/sorting/cycle_sort.py @@ -0,0 +1,37 @@ +def cycle_sort(arr): + writes = 0 + + for cycle_start in range(len(arr) - 1): + item = arr[cycle_start] + pos = cycle_start + + for i in range(cycle_start + 1, len(arr)): + if arr[i] < item: + pos += 1 + + if pos == cycle_start: + continue + + while item == arr[pos]: + pos += 1 + + arr[pos], item = item, arr[pos] + writes += 1 + + while pos != cycle_start: + pos = cycle_start + + for i in range(cycle_start + 1, len(arr)): + if arr[i] < item: + pos += 1 + + while item == arr[pos]: + pos += 1 + + arr[pos], item = item, arr[pos] + writes += 1 + +# Example usage: +arr = [5, 2, 7, 3, 4, 1, 6] +cycle_sort(arr) +print(arr)