| 1 | # Bucket Sort in Python |
| 2 | |
| 3 | def bucketSort(array): |
| 4 | |
| 5 | bucket = [] |
| 6 | |
| 7 | # Create empty buckets |
| 8 | |
| 9 | for i in range(len(array)): |
| 10 | |
| 11 | bucket.append([]) |
| 12 | |
| 13 | # Insert elements into their respective buckets |
| 14 | |
| 15 | for j in array: |
| 16 | |
| 17 | index_b = int(10 * j) |
| 18 | |
| 19 | bucket[index_b].append(j) |
| 20 | |
| 21 | # Sort the elements of each bucket |
| 22 | |
| 23 | for i in range(len(array)): |
| 24 | |
| 25 | bucket[i] = sorted(bucket[i]) |
| 26 | |
| 27 | # Get the sorted elements |
| 28 | |
| 29 | k = 0 |
| 30 | |
| 31 | for i in range(len(array)): |
| 32 | |
| 33 | for j in range(len(bucket[i])): |
| 34 | |
| 35 | array[k] = bucket[i][j] |
| 36 | |
| 37 | k += 1 |
| 38 | |
| 39 | return array |
| 40 | |
| 41 | array = [.42, .32, .33, .52, .37, .47, .51] |
| 42 | |