PDA

Click to See Complete Forum and Search --> : Quick prob I hope


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;

}

chilibean
Jan 30th, 2002, 02:58 PM
It's no huge problem, but next time just post a reply to the first thread that you started - don't create a new thread for the same problem.

The error is where the first

for(i=0;i<max;i++){

is. This code needs to have an = (equals sign) just like the other loop. Like this:

for(i=0;i<=max;i++){

The huge number was printed because one of your variables was basically undefined (no initialization).

Crazy_bee
Jan 31st, 2002, 07:48 AM
Thanks alot Chili!!