|
14 | 14 | # Best Case O(n); Average Case O(n); Worst Case O(n) |
15 | 15 |
|
16 | 16 | DEFAULT_BUCKET_SIZE=5 |
17 | | -defbucket_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 | +defbucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE): |
| 19 | +iflen(my_list) ==0: |
| 20 | +raiseException("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_inrange(int(bucket_count))] |
24 | 25 |
|
25 | | -bucket_count=(max_value-min_value)//bucket_size+1 |
26 | | -buckets=[] |
27 | | -foriinrange(bucket_count): |
28 | | -buckets.append([]) |
29 | 26 | foriinrange(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 | +returnsorted([buckets[i][j] foriinrange(len(buckets)) |
| 30 | +forjinrange(len(buckets[i]))]) |
32 | 31 |
|
33 | | -sorted_array=[] |
34 | | -foriinrange(len(buckets)): |
35 | | -buckets[i].sort() |
36 | | -forjinrange(len(buckets[i])): |
37 | | -sorted_array.append(buckets[i][j]) |
38 | | -returnsorted_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) foriteminuser_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) forninuser_input.split(',') iflen(user_input) >0] |
| 35 | +print(bucket_sort(unsorted)) |
0 commit comments