1
$\begingroup$

So, an exam's exercise asks me to find an alghoritm that can determine if counting sort is the best solution, otherwise use another optimal sorting algorithm.

Now i find that solutions for that question given by my professors are wrong because they do gave this as answer:( pseudocode)

Sorting(A,k) //where k is a value inserted by the user(?)
{ 
max=a[0];
for i=1 to n // n=dim
{
    if( a[i] > max) update max with a[i]
}
if( max <= k*n) then countingsort(A)

else heapsort(A);

return A;

Now that being said, if k is really a value inserted by the user, this makes that solution not really case sensitive or a proper valuation of counting sort time complexity. It seems to me that it isnt a general algorithm, which should be instead the purpose of that exercise i guess. my solution is:

Sort(A){
    int max, i;
    int min;
    if( arr[0] > arr[1]){
        max=a[0];
        min=a[1];
    }

    for(i= 2 ; i < n ; i++){
        if(a[i] > max) max=arr[i];

        else if( a[i]< min) min=arr[i];
    }
    range= max-min; // range for counting sort
    if(range/n < log n) counting sort(A,range);

    else mergesort/heapsort(A......);

    return A;
    }

If (range/n) < logn , it means that range < nlogn, which implies it ""should"" be better than other optimal sorting algorithms. It might be not the most accurate way but it seems like it should be something like that, shouldnt it?

$\endgroup$
0
$\begingroup$

I wouldn’t be too happy with your professor’s solution. You noticed that it will refuse to do a very fast counting sort if all item are either nk+1 or nk+2. That’s bad. What is fatal is that it will always do a counting sort if the array elements are all negative. (Please don’t tell me that a sorting algorithm which can only handle positive numbers would ever be considered).

$\endgroup$
4
  • 2
    $\begingroup$ since they are just learning, the point is to build the principal algorithm rather than to address all corner cases $\endgroup$ – Bulat Jul 9 '19 at 16:11
  • 1
    $\begingroup$ Negative numbers are not a “corner case”. And good algorithms don’t have “corner cases”. $\endgroup$ – gnasher729 Jul 10 '19 at 3:32
  • $\begingroup$ by changing int to unsigned we can easily avoid working with negatives. But this cosmetical change will result only in more paper-writing. $\endgroup$ – Bulat Jul 10 '19 at 8:39
  • $\begingroup$ By changing int to bool we have only two values and counting sort is always a good choice. Bulat, you are going down to Homer Simpson level here. $\endgroup$ – gnasher729 Jul 10 '19 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.