Question: 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!