From fecdc0357018e0ecfe731a98b741b82f82f02f2f Mon Sep 17 00:00:00 2001 From: echace13 <69325784+echace13@users.noreply.github.com> Date: Mon, 10 Oct 2022 21:16:05 +0530 Subject: [PATCH] Add Bucket Sort Implementation in Python (#48) * Add Bucket Sort Implementation in Python * feat: avoid text outputs Co-authored-by: Aarav Arora --- Python/bucketsort.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Python/bucketsort.py diff --git a/Python/bucketsort.py b/Python/bucketsort.py new file mode 100644 index 0000000..0687dd2 --- /dev/null +++ b/Python/bucketsort.py @@ -0,0 +1,42 @@ +# Python3 program to sort an array +# using bucket sort +def insertionSort(b): + for i in range(1, len(b)): + up = b[i] + j = i - 1 + while j >= 0 and b[j] > up: + b[j + 1] = b[j] + j -= 1 + b[j + 1] = up + return b + +def bucketSort(x): + arr = [] + slot_num = 10 # 10 means 10 slots, each + # slot's size is 0.1 + for i in range(slot_num): + arr.append([]) + + # Put array elements in different buckets + for j in x: + index_b = int(slot_num * j) + arr[index_b].append(j) + + # Sort individual buckets + for i in range(slot_num): + arr[i] = insertionSort(arr[i]) + + # concatenate the result + k = 0 + for i in range(slot_num): + for j in range(len(arr[i])): + x[k] = arr[i][j] + k += 1 + return x + +# Driver Code +x = [0.897, 0.565, 0.656, + 0.1234, 0.665, 0.3434] + +print(bucketSort(x)) +