Crazy_bee
Jan 30th, 2002, 09:26 AM
Every thing is working in this counting sort algorithm excetpt when i print it. Everything is sorted and it prints the first 9 elements of my array. Then the last element come up with some big negative number. Can someone help me please?
thanks
#include <stdio.h>
#include <malloc.h>
int main(int argc, char* argv[]){
int *x;
int a[10] = {23,2,53,6,98,52,43,76,3,11};
int b[10];
int max=0;
int i=0;
int amount=0;
int i2=0;
int bi=0;
/*Finds the maximum number in the array*/
for(i=0;i<10;i++){
if(a[i]>max)
max=a[i];
}
x = (int *)calloc(max, sizeof(int));/*allocates the memory for dynamic array*/
/*counts the number of reoccurances and places them into correct index of array x*/
for(i=0;i<max;i++){
amount = 0;
for(i2=0;i2<10;i2++){
if(a[i2]==i)
amount++;
}
x[i] = amount;
}
/*loops through array x and enters anything with one or more occurrances into array b*/
for(i=0;i<=max;i++){
if(x[i]!=0){
for(i2=0;i2<x[i];i2++){
b[bi]=i;
bi++;
}
}
}
/*prints the count sorted array*/
printf("This is count sorted array:\n");
for(i=0;i<10;i++){
printf("%d\n",b[i]);
}
return 0;
}
thanks
#include <stdio.h>
#include <malloc.h>
int main(int argc, char* argv[]){
int *x;
int a[10] = {23,2,53,6,98,52,43,76,3,11};
int b[10];
int max=0;
int i=0;
int amount=0;
int i2=0;
int bi=0;
/*Finds the maximum number in the array*/
for(i=0;i<10;i++){
if(a[i]>max)
max=a[i];
}
x = (int *)calloc(max, sizeof(int));/*allocates the memory for dynamic array*/
/*counts the number of reoccurances and places them into correct index of array x*/
for(i=0;i<max;i++){
amount = 0;
for(i2=0;i2<10;i2++){
if(a[i2]==i)
amount++;
}
x[i] = amount;
}
/*loops through array x and enters anything with one or more occurrances into array b*/
for(i=0;i<=max;i++){
if(x[i]!=0){
for(i2=0;i2<x[i];i2++){
b[bi]=i;
bi++;
}
}
}
/*prints the count sorted array*/
printf("This is count sorted array:\n");
for(i=0;i<10;i++){
printf("%d\n",b[i]);
}
return 0;
}