How do I combine 2 int arrays using recursion? It has to be from small to big. Right now it only combines the 5 first values of 20.
I want to combine these 2 arrays by sending both arrays to the function and 1 empty array (The new sorted one). Once in the function it needs to get the smallest number of both arrays. So for example the 1 in array A is smaller then the 2 array B. And then that value needs to be added to the new sorted array. And that until every number is sorted into the new array.
The result of the new array should be :
[ 1, 2, 3, 4, 5, 8, 13, 16, 21, 32, 34, 55, 64, 89, 128, 256, 512, 1024, , 2048, 5099]
I know there are better ways to do this but this is for a school project to learn recursion
This is my code : (Findme is the name of the class the function is in)
public int[] combineArray(int[] a, int[] b, int[] c, int i, int j, int x){
if(a[i] > a.length || b[j] > b.length ){
return c;
}
if(a[i] < b[j]){
c[x] = a[i];
combineArray(a, b, c, i + 1, j, x + 1);
}
if(a[i] > b[j]){
c[x] = b[j];
combineArray(a, b, c, i, j + 1, x + 1);
}
return c;
}
public static void main(String [] args)
{
findMe find = new findMe();
int[] a = {1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
int[] b = {4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
int[] c = new int[20];
int[] x = find.combineArray(a, b, c,0 , 0, 0);
for(int i = 0; i < find.combineArray(a, b, c,0 , 0, 0).length; i++){
System.out.println("On position : " + i + " is value " + x[i]);
}
}
for(int i = 0; i < find.combineArray(a, b, c,0 , 0, 0).length; i++){will call your method in each iteration, which is probably not what you want. You already have the result inxso just usefor(int i = 0; i < x.length; i++){a[i] > a.lengthare you sure you want to compare value in array with array length? My guess is you would want to pay attention to index soinot valuea[i]. Also>may be not enough sinceialso can't be equal to array length.