|
14 | 14 | # Best Case O(n); Average Case O(n); Worst Case O(n)
|
15 | 15 |
|
16 | 16 | DEFAULT_BUCKET_SIZE=5
|
17 |
| -def bucket_sort(my_list,bucket_size=DEFAULT_BUCKET_SIZE): |
18 |
| - if(my_list==0): |
19 |
| - print("you don't have any elements in array!") |
20 | 17 |
|
| 18 | +def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE): |
| 19 | + if len(my_list) == 0: |
| 20 | + raise Exception("Please add some elements in the array.") |
21 | 21 |
|
22 |
| - min_value=min(my_list) |
23 |
| - max_value=max(my_list) |
| 22 | + min_value, max_value = (min(my_list), max(my_list)) |
| 23 | + bucket_count = ((max_value - min_value) // bucket_size + 1) |
| 24 | + buckets = [[] for _ in range(int(bucket_count))] |
24 | 25 |
|
25 |
| - bucket_count=(max_value-min_value)//bucket_size+1 |
26 |
| - buckets=[] |
27 |
| - for i in range(bucket_count): |
28 |
| - buckets.append([]) |
29 | 26 | for i in range(len(my_list)):
|
30 |
| - buckets[(my_list[i]-min_value)//bucket_size].append(my_list[i]) |
| 27 | + buckets[int((my_list[i] - min_value) // bucket_size)].append(my_list[i]) |
31 | 28 |
|
| 29 | + return sorted([buckets[i][j] for i in range(len(buckets)) |
| 30 | + for j in range(len(buckets[i]))]) |
32 | 31 |
|
33 |
| - sorted_array=[] |
34 |
| - for i in range(len(buckets)): |
35 |
| - buckets[i].sort() |
36 |
| - for j in range(len(buckets[i])): |
37 |
| - sorted_array.append(buckets[i][j]) |
38 |
| - return sorted_array |
39 |
| - |
40 |
| - |
41 |
| - |
42 |
| - |
43 |
| -#test |
44 |
| -#best on python 3.7.3 |
45 |
| -user_input =input('Enter numbers separated by a comma:').strip() |
46 |
| -unsorted =[int(item) for item in user_input.split(',')] |
47 |
| -print(bucket_sort(unsorted)) |
| 32 | +if __name__ == "__main__": |
| 33 | + user_input = input('Enter numbers separated by a comma:').strip() |
| 34 | + unsorted = [float(n) for n in user_input.split(',') if len(user_input) > 0] |
| 35 | + print(bucket_sort(unsorted)) |
0 commit comments