
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program for Counting Sort
In this article, we will learn about the solution to the problem statement given below.
Problem statement− We are given an array, we need to sort the array using the concept of counting sort.
Counting sort is a technique in which we work on keys between a specific range. It involves counting the number of objects which have distinct key & values. Finally, we do arithmetic calculations to obtain the position of each object and display the output.
Now let’s observe the solution in the implementation below −
Example
def countSort(arr): # The output character array that will have sorted arr output = [0 for i in range(256)] # Create a count array initialized with 0 count = [0 for i in range(256)] # as strings are immutable ans = ["" for _ in arr] # count for i in arr: count[ord(i)] += 1 # position of character in the output array for i in range(256): count[i] += count[i-1] # output character array for i in range(len(arr)): output[count[ord(arr[i])]-1] = arr[i] count[ord(arr[i])] -= 1 # array of sorted charcters for i in range(len(arr)): ans[i] = output[i] return ans # main arr = "Tutorialspoint" ans = countSort(arr) print ("Sorted character array is "+str("".join(ans)))
Output −
Sorted character array is Taiilnooprsttu
All the variables are declared in the local scope and their references are seen in the figure above.
Conclusion
In this article, we have learned about how we can make a Python Program for Counting Sort
- Related Articles
- Java Program for Counting Sort
- C++ Program to Implement Counting Sort
- Counting Sort
- Python Program for Insertion Sort
- Python Program for Selection Sort
- Python Program for Bubble Sort
- Python Program for Cocktail Sort
- Python Program for Cycle Sort
- Python Program for Gnome Sort
- Python Program for Heap Sort
- Python Program for Merge Sort
- Python Program for Stooge Sort
- Python Program for Odd-Even Sort / Brick Sort
- Python Program for Binary Insertion Sort
- Python Program for Iterative Merge Sort

Advertisements