Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Java: Magic index in an array a[1..n] is defined to be an index such that a[ i ] = i. Given an array of integers,

Java:

Magic index in an array a[1..n] is defined to be an index such that a[ i ] = i. Given an array of integers, write a recursive method to find the first magic index from left to right. If one exists in the given array, return the index number i, otherwise return -1.

Here are some test cases. The first number is the size of the array.

Input1

6

-2 -2 3 -2 -2 -1

Output1

-1

-------------------------------------------

Input2

5

-1 7 2 3 4

Output2

2

SHOULD BE RECURSIVE METHOD

import java.util.*; import java.lang.*; import java.io.*;

class ProblemSolution{ public static int findMagicIndex(int[] a, int n){

// write a code } }

import java.util.*; import java.lang.*; import java.io.*; //Your program will be evaluated by this DriverMain class and several test cases.

public class DriverMain { public static void main(String[] args) { Scanner s = new Scanner(System.in); int N = s.nextInt(); int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = s.nextInt(); } ProblemSolution problemSolution = new ProblemSolution(); System.out.print(problemSolution.findMagicIndex(A, N)); } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Students also viewed these Databases questions