Skip to content

Create bucketsort.py #8139

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
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
23 changes: 23 additions & 0 deletions bucketsort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
def bucket_sort(arr):
if len(arr) == 0:
return arr

# Step 1: Create empty buckets
bucket_count = len(arr)
max_val, min_val = max(arr), min(arr)
bucket_range = (max_val - min_val) / bucket_count # Range of each bucket
buckets = [[] for _ in range(bucket_count)]

# Step 2: Distribute elements into buckets
for num in arr:
index = int((num - min_val) / bucket_range) # Find the correct bucket
if index == bucket_count: # Edge case for the max element
index -= 1
buckets[index].append(num)

# Step 3: Sort individual buckets and concatenate them
sorted_arr = []
for bucket in buckets:
sorted_arr.extend(sorted(bucket)) # Sort each bucket and extend to sorted array

return sorted_arr
Loading