Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # program to implement Bucket sort algorithm in python
- from itertools import chain
- # method that sorts the list
- def bucket_sort(myList):
- # finding the max element
- max_element = max(myList)
- # couting the number of digits in the max element
- digits = 0
- while max_element != 0:
- max_element = int(max_element / 10)
- digits += 1
- # raising divisor by number of digits
- divisor = 10
- d = divisor
- # loop while divisor does not become 0
- while divisor < d**(digits+1):
- # initializing radix as 10 empty lists
- Radix = [[] for _ in range(10)]
- # iterating over the list
- for element in myList:
- # finding the bucket where the element need to be inserted
- rem = element % divisor
- pos = int(rem / (divisor/10))
- # print(element, divisor, rem, pos)
- Radix[pos].append(element)
- print("\nAfter dividing by {0} the buckets are : ".format(divisor))
- print(Radix)
- # divide divisor by 10
- divisor = int(divisor * 10)
- myList = list(chain.from_iterable(Radix))
- # print(myList)
- return myList
- print("Program to implement Bucket sort algorithm in python")
- myList = list(map(int, input("\nEnter the elements to sorted as spaced integers : ").strip().split()))
- print("The list before sorting is : ")
- print(myList)
- myList = bucket_sort(myList)
- print("\nThe sorted list is : ")
- print(myList)
Add Comment
Please, Sign In to add comment