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?