|
13 | 13 | # Time Complexity of Solution: |
14 | 14 | # Best Case O(n); Average Case O(n); Worst Case O(n) |
15 | 15 |
|
16 | | -from __future__ import print_function |
17 | | -from insertion_sort import insertion_sort |
18 | | -import math |
19 | | - |
20 | | -DEFAULT_BUCKET_SIZE = 5 |
21 | | - |
22 | | -def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE): |
23 | | - if(len(myList) == 0): |
24 | | - print('You don\'t have any elements in array!') |
25 | | - |
26 | | - minValue = myList[0] |
27 | | - maxValue = myList[0] |
28 | | - |
29 | | - # For finding minimum and maximum values |
30 | | - for i in range(0, len(myList)): |
31 | | - if myList[i] < minValue: |
32 | | - minValue = myList[i] |
33 | | - elif myList[i] > maxValue: |
34 | | - maxValue = myList[i] |
35 | | - |
36 | | - # Initialize buckets |
37 | | - bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1 |
38 | | - buckets = [] |
39 | | - for i in range(0, bucketCount): |
| 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 | + |
| 21 | + |
| 22 | + min_value=min(my_list) |
| 23 | + max_value=max(my_list) |
| 24 | + |
| 25 | + bucket_count=(max_value-min_value)//bucket_size+1 |
| 26 | + buckets=[] |
| 27 | + for i in range(bucket_count): |
40 | 28 | buckets.append([]) |
| 29 | + for i in range(len(my_list)): |
| 30 | + buckets[(my_list[i]-min_value)//bucket_size].append(my_list[i]) |
| 31 | + |
| 32 | + |
| 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 |
41 | 39 |
|
42 | | - # For putting values in buckets |
43 | | - for i in range(0, len(myList)): |
44 | | - buckets[math.floor((myList[i] - minValue) / bucketSize)].append(myList[i]) |
45 | 40 |
|
46 | | - # Sort buckets and place back into input array |
47 | | - sortedArray = [] |
48 | | - for i in range(0, len(buckets)): |
49 | | - insertion_sort(buckets[i]) |
50 | | - for j in range(0, len(buckets[i])): |
51 | | - sortedArray.append(buckets[i][j]) |
52 | 41 |
|
53 | | - return sortedArray |
54 | 42 |
|
55 | | -if __name__ == '__main__': |
56 | | - sortedArray = bucketSort([12, 23, 4, 5, 3, 2, 12, 81, 56, 95]) |
57 | | - print(sortedArray) |
| 43 | +#test |
| 44 | +#besd 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)) |
0 commit comments