File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Bucket sort is a comparison sort algorithm that operates on elements by dividing them
3
+ into different buckets and then sorting these buckets individually. Each bucket is
4
+ sorted individually using a separate sorting algorithm or by applying the bucket
5
+ sort algorithm recursively. Bucket sort is mainly useful when the input is uniformly
6
+ distributed over a range.
7
+
8
+ Average & Best Case Time Complexity: O(n+k)
9
+ Worst Case Time Complexity: O(n*n)
10
+
11
+ Space complexity: O(n+k).
12
+ """
13
+
14
+ import math
15
+ def insertionSort (arr ):
16
+ for i in range (1 , len (arr )):
17
+ temp = arr [i ]
18
+ j = i - 1
19
+ while j >= 0 and arr [j ] > temp :
20
+ arr [j + 1 ] = arr [j ]
21
+ j -= 1
22
+ arr [j + 1 ] = temp
23
+ return arr
24
+
25
+ def bucketSort (arr ):
26
+ buckets = [[] for _ in range (len (arr ))] # Creating Buckets
27
+ divider = math .ceil ((max (max (arr ), len (arr ))+ 1 )/ len (buckets ))
28
+ # Adding numbers in buckets
29
+ for i in arr :
30
+ j = i // divider
31
+ buckets [j ].append (i )
32
+ # Sorting the buckers
33
+ for i in range (len (buckets )):
34
+ buckets [i ] = insertionSort (buckets [i ])
35
+
36
+ # Merging Buckets
37
+ k = 0
38
+ for i in range (len (buckets )):
39
+ for j in range (len (buckets [i ])):
40
+ arr [k ] = buckets [i ][j ]
41
+ k += 1
42
+
43
+ arr = [10 ,9 ,8 ,7 ]
44
+ bucketSort (arr )
45
+ print (arr )
You can’t perform that action at this time.
0 commit comments