Results 1 to 3 of 3

Thread: Quick prob I hope

  1. #1

    Thread Starter
    Lively Member Crazy_bee's Avatar
    Join Date
    Jul 2001
    Location
    Fitchburg
    Posts
    90

    Quick prob I hope

    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;

    }
    Don't ever Ginop before you Ginip

  2. #2
    Member
    Join Date
    Feb 2001
    Posts
    57
    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).

  3. #3

    Thread Starter
    Lively Member Crazy_bee's Avatar
    Join Date
    Jul 2001
    Location
    Fitchburg
    Posts
    90
    Thanks alot Chili!!
    Don't ever Ginop before you Ginip

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width