Skip to content
This repository has been archived by the owner on May 29, 2024. It is now read-only.

2 Sorting Algorithms Added in Python #1303

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions algorithms/Python/sorting/bucket_sort.py
Original file line number Diff line number Diff line change
@@ -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)
37 changes: 37 additions & 0 deletions algorithms/Python/sorting/cycle_sort.py
Original file line number Diff line number Diff line change
@@ -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)