Key_coder
Key_coder

Reputation: 536

How to optimize this code(Counting Sort)

I was trying to solve classic count sort problem. my o/p is right, but the time limit exceeded.How can I optimize the below code. I'm under memory limit.

Time Limit: 5 sec Source Limit: 50000 Bytes

class TurboStart {
    static int integerArray[] = new int[1000001];

    public static void main(String[] args) throws NumberFormatException,
            IOException {
        int  i, j;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        j = Integer.parseInt(reader.readLine());

        while (j-- > 0) {
            integerArray[Integer.parseInt(reader.readLine())]++;
        }

        for (i = 0; i < 1000001; i++) {
            while (integerArray[i]-- > 0) {
                System.out.println(i);
            }

        }
    }
}

Upvotes: 1

Views: 221

Answers (1)

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

Don't use System.out.println but some smarter way of writing the output(BufferedWriter?). Your code for the sort is good so the bottleneck should be the I/O(which is often problem with Java on programming competitions).

Upvotes: 1

Related Questions