|
| 1 | +#!/usr/bin/env python |
| 2 | +# Author: OMKAR PATHAK |
| 3 | +# This program will illustrate how to implement bucket sort algorithm |
| 4 | + |
| 5 | +# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the |
| 6 | +# elements of an array into a number of buckets. Each bucket is then sorted individually, either using |
| 7 | +# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a |
| 8 | +# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour. |
| 9 | +# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons |
| 10 | +# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates |
| 11 | +# involve the number of buckets. |
| 12 | + |
| 13 | +# Time Complexity of Solution: |
| 14 | +# Best Case O(n); Average Case O(n); Worst Case O(n) |
| 15 | + |
| 16 | +fromP26_InsertionSortimportinsertionSort |
| 17 | +importmath |
| 18 | + |
| 19 | +DEFAULT_BUCKET_SIZE=5 |
| 20 | + |
| 21 | +defbucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE): |
| 22 | +if(len(myList) ==0): |
| 23 | +print('You don\'t have any elements in array!') |
| 24 | + |
| 25 | +minValue=myList[0] |
| 26 | +maxValue=myList[0] |
| 27 | + |
| 28 | +# For finding minimum and maximum values |
| 29 | +foriinrange(0, len(myList)): |
| 30 | +ifmyList[i] <minValue: |
| 31 | +minValue=myList[i] |
| 32 | +elifmyList[i] >maxValue: |
| 33 | +maxValue=myList[i] |
| 34 | + |
| 35 | +# Initialize buckets |
| 36 | +bucketCount=math.floor((maxValue-minValue) /bucketSize) +1 |
| 37 | +buckets= [] |
| 38 | +foriinrange(0, bucketCount): |
| 39 | +buckets.append([]) |
| 40 | + |
| 41 | +# For putting values in buckets |
| 42 | +foriinrange(0, len(myList)): |
| 43 | +buckets[math.floor((myList[i] -minValue) /bucketSize)].append(myList[i]) |
| 44 | + |
| 45 | +# Sort buckets and place back into input array |
| 46 | +sortedArray= [] |
| 47 | +foriinrange(0, len(buckets)): |
| 48 | +insertionSort(buckets[i]) |
| 49 | +forjinrange(0, len(buckets[i])): |
| 50 | +sortedArray.append(buckets[i][j]) |
| 51 | + |
| 52 | +returnsortedArray |
| 53 | + |
| 54 | +if__name__=='__main__': |
| 55 | +sortedArray=bucketSort([12, 23, 4, 5, 3, 2, 12, 81, 56, 95]) |
| 56 | +print(sortedArray) |
0 commit comments