1. 程式人生 > 實用技巧 >Counting sort in Java Not only non-negative numbers

Counting sort in Java Not only non-negative numbers

Implement a method to sort a given array of ints using counting sort.

The method should process numbers from -10 to 20 inclusive.

Note: the method must change elements of the input array.

Sample Input 1:

2 3 -1 -2 4

Sample Output 1:

-2 -1 2 3 4
import java.util.Scanner;
import java.util.Arrays;

public class Main {

    public static void countingSort(int[] numbers) {
        int min = -10;
        int max = 20;
        int[] c = new int[max - min + 1];
        for (int number : numbers) {
            c[number - min] += 1;
        }
        int i = 0;
        for (int j = 0; j < c.length; j++) {
            while (c[j] > 0) {
                c[j] -= 1;
                numbers[i++] = j + min;
            }
        }
    }

    /* Do not change code below */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        final String elements = scanner.nextLine();
        final int[] array = Arrays.stream(elements.split("\\s+"))
                .mapToInt(Integer::parseInt)
                .toArray();
        countingSort(array);
        Arrays.stream(array).forEach(e -> System.out.print(e + " "));
    }
}