# split array

• 03-16-2013
rec0o
split array
hi! i want to splt the array into sections of 2 values, recursively. the objective its to do the average.
i have this input and output, that its correct:
> media_recursiva a 1 a 2 a 4 a 5 a 2 a 3 a 5 a 6
1.000
1.500
3.000
3.500

("a 1" means add the value 1)

but mine its wrong, it gives to me this:
1.000
1.000
2.500
3.000

Code:

```float media(int arr[], int count) {     while(count != 0){         if(count==1)             return arr[0];         else if(count ==2){             return ((arr[0] + arr[1])/2);         }         else{             int *fHalf = arr;//first half of array             int *sHalf = arr + (count/2);//second half             return (media(fHalf, (count/2)) + media(sHalf, (count/2)))/2;         }     }        }```
thanks
• 03-16-2013
Why the split of first half and second half? Problem is, it makes your code far less intuitive to modify or debug, and I don't see any gain from doing it - just the opposite.
• 03-17-2013
Malcolm McLean
Quote:

Originally Posted by rec0o
Code:

```float media(int arr[], int count) {     while(count != 0){         if(count==1)             return arr[0];         else if(count ==2){             return ((arr[0] + arr[1])/2);         }         else{             int *fHalf = arr;//first half of array             int *sHalf = arr + (count/2);//second half             return (media(fHalf, (count/2)) + media(sHalf, (count/2)))/2;         }     }        }```
thanks

The while is wrong.
If count == 1 or count == 2 that is your terminating condition, and you return a value. Otherwise you call media() twice with the first half and second half of the array. You don't loop within the function.
• 03-17-2013
rec0o
i removed the while but it stills wrong. maybe its because im giving a int array[] as parameter and its rounding down
• 03-17-2013
Quote:

Originally Posted by rec0o
i removed the while but it stills wrong. maybe its because im giving a int array[] as parameter and its rounding down

Clearly time for a double - or float. you'll never get 3.5 from an int!
• 03-17-2013
whiteflags
Quote:

hi! i want to splt the array into sections of 2 values, recursively. the objective its to do the average.
You'd end up calculating the following

(1 + (2 + (3 + (4 + 5)))) / 2 / 2 / 2 / 2

Is there really no concern that this is entirely wrong?