U have an array of +ve integers arranged in the descending
order . Write a functionb thast take an integer & an integer
array as an integer and returns the position of the given
integer in the array , if the integer is not present in the
array it should return -1 . the serching technique that u
use should be very efficient both in terms of time & memory.

Answer Posted / siddarth pillai

public class Test
{
public static void main(String args[])
{
int[] arr = {99,56,31,22,17,11,9,2};
int no=11;

int position = checkPos(arr,no);

if(position == -1)
System.out.println("No such number exists in the array.");
else
System.out.println("Number "+no+" is at position "+position);
}
public static int checkPos(int[] arr,int no)
{
int first = 0;
int last = arr.length;
int mid = (first+last)/2;
int LoopCount = 0;
int MaxLoopCount = arr.length/2;

System.out.println("first : "+first+" last : "+last+" mid : "+mid);

while((arr[mid]!=no) && (LoopCount<MaxLoopCount))
{
if(no>arr[mid])
{
first = 0;
last = mid;
mid =(first+last)/2;
System.out.println("first : "+first+" last : "+last+" mid : "+mid);
}
else if(no<arr[mid])
{
last=arr.length;
first = mid;
mid =(first+last)/2;
System.out.println("first : "+first+" last : "+last+" mid : "+mid);
}
LoopCount++;

}
if(no == arr[mid])
return mid;
else
return -1;

}
}

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

please do tell me who the editor-in-chief of the Asian Age is as of 2011-12

1458


Why you want to come in Marketing although you have done your MBA in Finance?

1668


What is diff bet lotus and exchange and which is good in messing only?

1881


How many categories of workes are there in LIC of india?what are they?

1926


you do not have MBA degree. why should we appoint you as Deputy General Manager of CSD Bangladesh?

1521






Hi ,can any one tell me wt 's SOA mean ?

1680


I am a b.tech(IT) graduate.What are the b.tech subject topics i have to prepare for sbi clerk interview as i was told that q's will be there in our specialised subjects

1515


Difference between form of a word and its function.

1748


what is marketing, purchase and sale?

1583


Why Amartya sen got Nobel prize? how his theory proved useful for developing nations?

1537


i want to be manager in sotre and purchase

1529


WHAT IS MEANING OF M/S IN RETAIL SENSE ????

1572


can server request to the client:yes/no give the reasion atleast 3

1417


what is GRN ? When to raise GRN?

2097


My technical interview of wipro is on 22 jan.Please send me some questions regarding c & c++.My email address is sjotkaur@gmail.com.

1650