Translate

Saturday, 1 February 2014

Counting Sort


Comparison Sorting
Quick sort usually has a running time of n log(n), but is there an algorithm that can sort even faster? In general, this is not possible. Most sorting algorithms arecomparison sorts, which means they sort a list just by comparing the elements with each other. A comparison sort algorithm cannot beat n log(n) (worst-case) running time, since that is the minimum number of comparisons needed to know where to place each element. For more details, you can see these notes (PDF).
Alternative Sorting
However, for certain types of input, it is more efficient to use a non-comparison sorting algorithm. This will make it possible to sort lists even in linear time. These challenges will cover Counting Sort, a fast way to sort lists where the elements have a small number of possible values, such as integers within a certain range. We will start with an easy task - counting.

Challenge
Given a list of integers, can you count and output the number of times each value appears?
Hint: There is no need to sort the data, you just need to count it.
Input Format
There will be two lines of input:
  • n - the size of the list
  • ar - n numbers that makes up the list
Output Format
Output the number of times every number from 0 to 99 (inclusive) appears in the list.
Constraints
100 <= n <= 1000000
0 <= x < 100 , x ∈ ar
Sample Input
100
63 25 73 1 98 73 56 84 86 57 16 83 8 25 81 56 9 53 98 67 99 12 83 89 80 91 39 86 76 85 74 39 25 90 59 10 94 32 44 3 89 30 27 79 46 96 27 32 18 21 92 69 81 40 40 34 68 78 24 87 42 69 23 41 78 22 6 90 99 89 50 30 20 1 43 3 70 95 33 46 44 9 69 48 33 60 65 16 82 67 61 32 21 79 75 75 13 87 70 33 
Sample Output
0 2 0 2 0 0 1 0 1 2 1 0 1 1 0 0 2 0 1 0 1 2 1 1 1 3 0 2 0 0 2 0 3 3 1 0 0 0 0 2 2 1 1 1 2 0 2 0 1 0 1 0 0 1 0 0 2 1 0 1 1 1 0 1 0 1 0 2 1 3 2 0 0 2 1 2 1 0 2 2 1 2 1 2 1 1 2 2 0 3 2 1 1 0 1 1 1 0 2 2 
1 1 3 3 6 8 9 9 10 12 13 16 16 18 20 21 21 22 23 24 25 25 25 27 27 30 30 32 32 32 33 33 33 34 39 39 40 40 41 42 43 44 44 46 46 48 50 53 56 56 57 59 60 61 63 65 67 67 68 69 69 69 70 70 73 73 74 75 75 76 78 78 79 79 80 81 81 82 83 83 84 85 86 86 87 87 89 89 89 90 90 91 92 94 95 96 98 98 99 99 

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int B[100];
int main() 
{
   long int n,i;
   scanf("%ld",&n);
   int A[n];
   for(i=0;i<n;i++)
        scanf("%d",&A[i]);
   
    for(i=0;i<n;i++)
        B[A[i]]+=1;
   
    for(i=0;i<100;i++)
        printf("%d ",B[i]);

             printf("\n\n");

    for(i=0;i<100;i++)
        while(B[i]--)
           printf("%ld ",i);

return 0;
}

No comments:

Post a Comment