Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Parallel Count Sort
Next article icon

Java Program for Counting Sort

Last Updated : 14 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence.

Java




// Java implementation of Counting Sort
import java.io.*;
public class CountingSort {
    void sort(char arr[])
    {
        int n = arr.length;
 
        // The output character array that will have sorted arr
        char output[] = new char[n];
 
        // Create a count array to store count of individual
        // characters and initialize count array as 0
        int count[] = new int[256];
        for (int i = 0; i < 256; ++i)
            count[i] = 0;
 
        // store count of each character
        for (int i = 0; i < n; ++i)
            ++count[arr[i]];
 
        // Change count[i] so that count[i] now contains actual
        // position of this character in output array
        for (int i = 1; i <= 255; ++i)
            count[i] += count[i - 1];
 
        // Build the output character array
        for (int i = 0; i < n; ++i) {
            output[count[arr[i]] - 1] = arr[i];
            --count[arr[i]];
        }
 
        // Copy the output array to arr, so that arr now
        // contains sorted characters
        for (int i = 0; i < n; ++i)
            arr[i] = output[i];
    }
 
    // Driver method
    public static void main(String args[])
    {
        CountingSort ob = new CountingSort();
        char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o',
                      'r', 'g', 'e', 'e', 'k', 's' };
 
        ob.sort(arr);
 
        System.out.print("Sorted character array is ");
        for (int i = 0; i < arr.length; ++i)
            System.out.print(arr[i]);
    }
}
/*This code is contributed by Rajat Mishra */
 
 
Output: 
Sorted character array is eeeefggkkorss

 

Time Complexity: O(n+k) where n is the number of elements in the input array and k is the range of input. 
Auxiliary Space: O(n+k)

Please refer complete article on Counting Sort for more details!
 



Next Article
Parallel Count Sort
author
kartik
Improve
Article Tags :
  • DSA
  • Java Programs
  • Sorting
  • counting-sort
Practice Tags :
  • Sorting

Similar Reads

  • Counting Sort - Data Structures and Algorithms Tutorials
    Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
    9 min read
  • Median and Mode using Counting Sort
    Given an n sized unsorted array, find median and mode using counting sort technique. This can be useful when array elements are in limited range. Examples: Input : array a[] = {1, 1, 1, 2, 7, 1} Output : Mode = 1 Median = 1 Note: Median is average of middle two numbers (1 and 1) Input : array a[] =
    12 min read
  • Implementing Counting Sort using map in C++
    Counting Sort is one of the best sorting algorithms which can sort in O(n) time complexity but the disadvantage with the counting sort is it's space complexity, for a small collection of values, it will also require a huge amount of unused space. So, we need two things to overcome this: A data struc
    2 min read
  • Counting Sort - Python
    Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
    7 min read
  • C Program for Counting Sort
    Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Algorithm: Step 1: StartStep 2 : Find Larg
    3 min read
  • Java Program for Counting Sort
    Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Java Code // Java implementation of Counti
    2 min read
  • Parallel Count Sort
    What is Parallel Count Sort?Parallel count sort is an efficient algorithm that sorts an array of elements in a parallel manner. It is a variation of the classic count sort algorithm which is used to sort a collection of objects based on their frequency. The algorithm is based on the idea of counting
    12 min read
  • Problem based on Counting Sort

    • Find duplicates in an Array with values 1 to N using counting sort
      Given a constant array of N elements which contain elements from 1 to N - 1, with any of these numbers appearing any number of times.Examples: Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explana
      11 min read

    • Kth smallest or largest element in unsorted Array using Counting Sort
      Given an array arr[] and a number K, where K is smaller than the size of the array, we need to find the Kth smallest element in the given array. It is given that array elements can be repeated (not limited to distinct). Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {
      7 min read

    • Sort an array of 0s, 1s and 2s (Simple Counting)
      Given an array A[] consisting of 0s, 1s, and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s, and all 2s in last. Examples: Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2} Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2,
      11 min read

  • Counting Sort Visualization using JavaScript
    GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Counting Sort using JavaScript. We will see how the frequencies of elements are stored and how we get the final sorted array. We will also visualize the time complexity of Counting Sort.
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences