Use recursion to solve the below: a)) Write a method when you pass it an array o
ID: 3851684 • Letter: U
Question
Use recursion to solve the below:
a)) Write a method when you pass it an array of integers, it splits the array
into odd an even sections. It will put the odd numbers at the beginning of the
array and the even numbers at the end of the array. The algorithm should work
even if the array is all odd or all even.
Example: If you input [1,2,3,4,5,6,7,8.9]
The output would be: [1,3,5,7,9,2,4,6,8]
b)) Ask the user to read another integer which represents the
size of the array to be read in. After you read the integer n, read that many
integers and store them in an array, and call the second method and print the
resulting array which is split into odd and even section.
pleae make sure u use only one recursion method to solve this problem
Explanation / Answer
[a]
public static int[] SplitArray(int [] Arr)
{
int[] x = Arr;
int n = Arr.length;
int j = 0;
//To Store Odd and Even Value Repestive Array
for(int i = 0; i < n; i++)
{
if(x[i] % 2 != 0)
{
Arr[j] = x[i];
j++;
}
}
for(int i = 0; i < n; i++)
{
if(x[i] % 2 == 0)
{
Arr[j] = x[i];
j++;
}
}
return( x ); // Return the **reference** (location) of the array
}
[b]
import java.util.Scanner;
public class OddEvenPrint
{
public static void main(String[] args)
{
int n, j = 0, k = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
int odd[] = new int[n];
int even[] = new int[n];
System.out.println("Enter all the elements:");
//To Store User input Value into Array
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
//To Store Odd and Even Value Repestive Array
for(int i = 0; i < n; i++)
{
if(a[i] % 2 != 0)
{
odd[j] = a[i];
j++;
}
else
{
even[k] = a[i];
k++;
}
}
//To Print Odd Element
System.out.print("Odd:");
if(j > 1)
{
for(int i = 0;i < (j-1); i++)
{
System.out.print(odd[i]+",");
}
System.out.print(odd[j-1]);
}
else
{
System.out.println("No number");
}
//To Print Even Number
System.out.println("");
System.out.print("Even:");
if(k > 1)
{
for(int i = 0; i < (k-1); i++)
{
System.out.print(even[i]+",");
}
System.out.print(even[k-1]);
}
else
{
System.out.println("No number");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.