countSort() function not working
Oct 20, 2014 at 2:26pm UTC
I've written the following code.
When I give input an array it outputs the same unsorted inputted array.
Example:
Input:
5
6 1 8 3 2
Output:
6 1 8 3 2
But the output should be sorted : 1 2 3 6 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <iostream>
using namespace std;
void counting_sort(int *array,int size,int range)
{
int i=0,j=0;
int *c = new int [range+1]; // RANGE = value of K
int *result = new int [size]; // result-output, c-temporary array
for (i=0;i<range;i++)
c[i]=0; // initialize c to 0
for (i=0;i<size;i++)
c[array[i]]++; // count the numbers
for (i=1;i<range;i++)
c[i]=c[i]+c[i-1]; // determine the position of numbers
for (j=size-1;j>-1;j--)
{
result[c[array[j]]-1]=array[j];
c[array[j]]--;
}
}
int main()
{
int n;
while (scanf("%d" ,&n) && n!=0)
{
int input[n];
for (int i=0; i<n; i++)
cin>>input[i];
counting_sort(input,n,100);
printf("%d" ,input[0]);
for (int i=1;i<n;i++)
printf(" %d" ,input[i]);
printf("\n" );
}
return 0;
}
Last edited on Oct 20, 2014 at 2:27pm UTC
Oct 20, 2014 at 3:27pm UTC
Whatever else counting_sort() is doing, it's not modifying the array you passed to it. You're printing out your original array again.
Your sorted array is in "result", not "input"
Topic archived. No new replies allowed.