views:

27

answers:

1

Hi I have found this question in the one site which was about counting sort algorithm and this question was an exercise ! I solved this and I want to know that is this correct?

Exercise: Use The idea of Counting Sort algorithm and provide an algorithm with n integer in the range 0 to k, in time O (1) replied that how many of these n elements are in the interval [a, b] ? Of course, your algorithm should process n elements that can help you take the numbers between a and b (0 ≤ a, b ≤ k) . This basic process should be in time Θ (n + k) .

this is my algorithm:

Algorithm Range(A,k,a,b)
{Consider C is the output array of PartOfCountingSort algorithm}
C<--PartOfCountingSort(A,k)
//finding the number of elements between a and b
numberOfElements<-- C[b]-C[a]+1
return numberOfElements
//end of the Range algorithm
------------------------------------
PartOfCountingSort(A,k)  // Theta(n+k)
OutPut: array C is the output of this algorithm
   for  i<-- 1 to k
      C[i]<-- 0
   for  j<-- 1 to A. length
      C[A[j]]<--C[A[j]]+1
   for  i<--2 to k
      C[i]<--C[i]+C[i-1]
+2  A: 

It should be

numberOfElements<-- C[b]-C[a - 1]

Recall that C[i] = number of elements lower than or equal to i. You don't want to subtract those equal to a.

You should also handle the cases where a = 0 and maybe when a = 1 too.

IVlad
@matin1234 - no, for `a = 0` you return `C[b]` and for `a = 1` you return `C[b] - C[0]`. The problem is that you don't initialize `C[0]` in your `PartOfCountingSort` function. It should also be initialized to 0.
IVlad
also why should I handle "a=0,a=1"? I think I should check this"a=b or b<a" yes?
I also initialize the C[0] with the first for loop and I think all the ranges in the counting sort are begin with 0 !!
@matin1234 - you can check if `b < a` if you want, in that case there's no solution. However, your problem statement says `[a, b]` is an interval, so normally `b` cannot be lower than `a`. You should handle `a = 0` because `C[b] - C[a - 1]` is `C[b] - C[-1]` when `a = 0`, and `C[-1]` doesn't make sense. You don't initialize `C[0]` in the first loop because your first loop starts from `1`. It needs to start from `0`.
IVlad
awww,now I get it ,really thanks :)