Getting run error for count sort

i used count sort algo yet i am getting run-error

Hello @S19LPPP0159,

You are getting run error because your program is trying to access memory that has not been allocated.

count[10]={0};
This is the error.
The index of the count array refers to the element of the input array.
So, how are you so sure that there would be no element greater than 9 in the input array?

Solution is given in the question:
0<=Ai<=10^6
This should be the size of array.

Hope, you have understood your mistake.
Don’t worry it’s a common mistake everyone does.
It will eliminate itself by practice.

Give a like, if you are satisfied.

2 Likes

modifying the code to 10^6 gives wrong answer.

What is logic for below code?

No, requirement of following code:
for(int i=1;i<n;i++)
{
count[i]=count[i]+count[i-1]; //ADDING ITH ELEMENT TO PREVIOUS ELEMENT [i-1]
}

The logic of following code is wrong:
int out[n];
for(int i=0;i<n;i++)
{
out[count[arr[i]]-1]=arr[i];
count[arr[i]]–;
}

Modification:

  1. Find the maximum element of the input array as max.
  2. Then use following code:
    int i=0;
    for(int j=0,j<=max;j++){
    while(count[j]>0){
    arr[i]=j;
    i++;
    count[j]–;
    }
    }

Hope, it would help.
if you still have doubt, let me know.