As you can see in this code I just did how to sort positive integer numbers using counting sort. but my requirement is I have to take the negative and positive numbers as input then have to sort the array using counting sort. finding the lowest value in the array then taking input is not allowed. I don't know what will be the logic and solution for this.
note: if I take any negative number in my input. the output shows 0 for that value.
Input: 9, 8, 6, -7, 2, 1
output: -7, 1, 2, 6, 8, 9
int k=0;
void Counting_Sort(int A[],int B[],int n)
{
int C[k+1];
for(int i=0; i<=k; i++)
{
C[i]=0;
}
for(int j=1; j<=n; j++)
{
C[A[j]]++;
}
for(int i=1; i<=k; i++)
{
C[i]+=C[i-1];
}
for(int j=n; j>=1; j--)
{
B[C[A[j]]]=A[j];
C[A[j]]=C[A[j]]-1;
}
}
// Driver code
int main()
{
int n;
cout<<"Enter the size of the array :";
cin>>n;
int A[n],B[n];
for(int i=1; i<=n; i++)
{
cin>>A[i];
if(A[i]>k)
{
/*It will modify k if an element
occurs whose value is greater than k*/
k=A[i];
}
}
Counting_Sort(A,B,n);
/*It will print the sorted sequence on the
console*/
for(int i=1; i<=n; i++)
{
cout<<B[i]<<" ";
}
cout<<endl;
return 0;
}
There's a bit of constraint on this problem, but this can be solve by reversing the negative number back to a positive one, and storing negatives and positives in 2 different arrays. Then you can print the negative array first, after that print the positive array:
Result:
Another test: