m2skills

Counting sort python

Sep 28th, 2017
541
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. # program to implement counting sort algorithm in python
  2.  
  3. def countingSort(myList):
  4.    
  5.     # finding the length, min, max of the recieved list of numbers
  6.     length = len(myList)
  7.     minElement = min(myList)
  8.     maxElement = max(myList)
  9.    
  10.     # creating a count list with initial values as zeros
  11.     countList = [0 for i in range(minElement, maxElement+1)]
  12.    
  13.     # counting number of times each element occurs in the list and storing the count in the coutList
  14.     for element in myList:
  15.         countList[element - minElement] = countList[element - minElement] + 1
  16.  
  17.     # starting from the min element upto max element
  18.     # we insert values according to their count in the new list in sorted order
  19.     element = minElement
  20.     myList.clear()
  21.     for Count in countList:
  22.         myList += [element for i in range(Count)]
  23.         element += 1
  24.    
  25.     return myList
  26.    
  27. print("Program to implement Counting sort algorithm in python")
  28. myList = list(map(int, input("\nEnter the elements to sorted as spaced integers : ").strip().split()))
  29. print("The list before sorting is : ")
  30. print(myList)
  31. myList = countingSort(myList)
  32. print("\nThe sorted list is : ")
  33. print(myList)
Add Comment
Please, Sign In to add comment