Could you explain me how the following two algorithms work?
int countSort(int arr[], int n, int exp)
{
int output[n];
int i, count[n] ;
for (int i=0; i < n; i++)
count[i] = 0;
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%n ]++;
for (i = 1; i < n; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%n] - 1] = arr[i];
count[(arr[i]/exp)%n]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
void sort(int arr[], int n)
{
countSort(arr, n, 1);
countSort(arr, n, n);
}
I wanted to apply the algorithm at this array:

After calling the function countSort(arr, n, 1) , we get this:

When I call then the function countSort(arr, n, n) , at this for loop:
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%n] - 1] = arr[i];
count[(arr[i]/exp)%n]--;
}
I get output[-1]=arr[4].
But the array doesn't have such a position...
Have I done something wrong?
EDIT:Considering the array arr[] = { 10, 6, 8, 2, 3 }, the array count will contain the following elements:

what do these numbers represent? How do we use them?
Counting sort is very easy - let's say you have an array which contains numbers from range
1..3:[3,1,2,3,1,1,3,1,2]You can count how many times each number occurs in the array:
count[1] = 4count[2] = 2count[3] = 3Now you know that in a sorted array,
number
1will occupy positions0..3(from0tocount[1] - 1), followed bynumber
2on positions4..5(fromcount[1]tocount[1] + count[2] - 1), followed bynumber
3on positions6..8(fromcount[1] + count[2]tocount[1] + count[2] + count[3] - 1).Now that you know final position of every number, you can just insert every number at its correct position. That's basically what
countSortfunction does.However, in real life your input array would not contain just numbers from range
1..3, so the solution is to sort numbers on the least significant digit (LSD) first, then LSD-1 ... up to the most significant digit.This way you can sort bigger numbers by sorting numbers from range
0..9(single digit range in decimal numeral system).This code:
(arr[i]/exp)%nincountSortis used just to get those digits.nis base of your numeral system, so for decimal you should usen = 10andexpshould start with1and be multiplied by base in every iteration to get consecutive digits.For example, if we want to get third digit from right side, we use
n = 10andexp = 10^2:x = 1234,(x/exp)%n = 2.This algorithm is called Radix sort and is explained in detail on Wikipedia: http://en.wikipedia.org/wiki/Radix_sort