I am confused on how to do these methods. I am trying to review but this is maki
ID: 3551093 • Letter: I
Question
I am confused on how to do these methods. I am trying to review but this is making no sense. This is what the "skeleton" of the program looks like. We are supposed to use recursion for the array.
// Divide and conquer as was done in class EXCEPT do not divide the array
// into two halves but divide it into a left half, a middle element, and a
// right half. The maxBlock of an empty array does not make sense so you
// should never call the recursive method on an empty array.
public static int maxBlock(int data[], int n) {
// Divide and conquer
public static void out1(int data[], int n) {
// 1 element on the left, the rest of the array on the right
public static void out2(int data[], int n) {
// All but 1 element on the left and the remaining element on the right
public static void out3(int data[], int n) {
// Swap the first and last elements, reverse the remaining array
public static void reverse(int data[], int n) {
// Return the index of the largest element in the array. Divide and conquer
// with a left half, a middle element, and a right half. The largest element
// of an empty array does not make sense so you should never call the
// recursive method on an empty array.
public static int largest(int data[], int n) {
Explanation / Answer
use this code as referance for a recursive function
import java.util.Scanner;
public class RecursionLargestInArray
{
public static void main (String[] args)
{
int max = -999;
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < myArray.length; i++)
myArray[i] = scan.nextInt();
for (int i = 0; i < myArray.length; i++)
System.out.println(myArray[i]);
System.out.println("In the array entered, the larget value is "
+ getLargest(myArray, max) + ".");
}
public static int getLargest(int[] myArray, int max)
{
int i = 0, j = 0, tempmax = 0;
if (myArray.length == 1)
{
return myArray[0] > max ? myArray[0] : max;
}
else if (max < myArray[i])
{
max = myArray[i];
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
else
{
int[] tempArray = new int[myArray.length-1];
for (i = 1; i < myArray.length; i++)
{
tempArray[j] = myArray[i];
j++;
}
tempmax = getLargest(tempArray, max);
return tempmax;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.