Home > Mobile >  Function argument function cannot operate with array
Function argument function cannot operate with array

Time:11-18

I was trying to make a functional bucket sort array in c with a variable funtion parameter in order to sort each bucket, so I tried to pass the bubblesort algorithm but it doesn't seems to do anything with each bucket, my question is: What am I doing wrong?, at my first glance it seems that there aren't mistakes in my code: (sorry for the mess)

void bubblesort (int arr[], unsigned char size) {
    size /= sizeof(int);
    for (unsigned char i = 0; i < size - 1; i  )
    for (unsigned char j = 0; j < size - i - 1; j  )
    if (arr[j] > arr[j 1])
        arr[j]   = arr[j]   arr[j 1],
        arr[j 1] = arr[j] - arr[j 1],
        arr[j]   = arr[j] - arr[j 1];
}

/* More sorting algorithms */

void bucketsort (int arr[], unsigned char size, unsigned char n, void sort(int[],unsigned char)) {
    // to be fixed
    size /= sizeof(int); int *bucket[n]; unsigned char s[n];
    for (unsigned char i = 0; i < n; i  ) s[i] = 0, bucket[i] = NULL;
    int min = arr[0], max = arr[0];
    for (unsigned char i = 1; i < size; i  ) { 
        if (arr[i] < min) min = arr[i];
        if (arr[i] > max) max = arr[i];
    } for (unsigned char i = 0; i < size; i  )
        s[n*(arr[i]-min)/(max-min 1)]  ,
        bucket[n*(arr[i]-min)/(max-min 1)] = (int*)realloc(bucket[n*(arr[i]-min)/(max-min 1)],s[n*(arr[i]-min)/(max-min 1)]*sizeof(int)),
        bucket[n*(arr[i]-min)/(max-min 1)][s[n*(arr[i]-min)/(max-min 1)]-1] = arr[i];
    for (int i = 0; i < n; i  ) {for (int j = 0; j < s[i]; j  ) printf("%d ",bucket[i][j]); printf("\n");}
    for (unsigned char i = 0; i < n; i  ) sort(bucket[i],s[i]), fflush(NULL);
    for (int i = 0, index = 0; i < n; i  ) for (int j = 0; j < s[i]; j  ) arr[index  ] = bucket[i][j];
}

int main (void) {
    int a[] = {3,6,4,9,1,7,5,8,2,0};
    bucketsort(a,sizeof(a),4,bubblesort);
    for (signed char i = 0; i < (signed char)(sizeof(a)/sizeof(int)); i  ) printf("%d, ",a[i]);
 }

In my function parameter I´ve tried replacing the [] with * but it doesn't make any difference.

CodePudding user response:

You have to remove the line "size /= sizeof(int)" - and the size is correct

    void bubblesort (int arr[], unsigned char size) {
    //    size /= sizeof(int);
        for (unsigned char i = 0; i < size - 1; i  )
        for (unsigned char j = 0; j < size - i - 1; j  )
        if (arr[j] > arr[j 1])
            arr[j]   = arr[j]   arr[j 1],
            arr[j 1] = arr[j] - arr[j 1],
            arr[j]   = arr[j] - arr[j 1];
    }

Test:

    1 2 0 
    3 4 
    6 7 5 
    9 8 
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ~"[Thread 26424.0x564c exited with code 0]
  • Related