Counting Sort

medium Searching and Sorting

Problem

Read an array of integers between 0 and 1000. Print it sorted in ascending order. Use counting sort (no comparisons between elements).

Constraints

  • 1 <= n <= 10^5
  • 0 <= a[i] <= 1000

Examples

Input

7
4 2 2 8 3 3 1

Output

1 2 2 3 3 4 8

Solutions

Best approachTime O(n + k)Space O(k)

When values are in a small range, we can count them instead of comparing. The time is O(n + range).

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Sort an array in ascending order.
 * Input   : n, then n integers.
 * Output  : The sorted array.
 * Approach: Count the values.
 * Time    : O(n + k)
 * Space   : O(k)
 * Java    : 8 or newer.
 */
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static int[] solve(int[] a) {
        // Step 1: One counter for each possible value 0..1000.
        int[] counts = new int[1001];

        // Step 2: Count how often each value appears.
        for (int value : a) {
            counts[value]++;
        }

        // Step 3: Write the values back in order. Each value is written as many times as it was counted.
        int index = 0;
        for (int value = 0; value <= 1000; value++) {
            for (int times = 0; times < counts[value]; times++) {
                a[index] = value;
                index++;
            }
        }
        return a;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
    }
}
Hints (1)
  1. What is the cost when the range is large?