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 do tell me who the editor-in-chief of the Asian Age is as of 2011-12
Why you want to come in Marketing although you have done your MBA in Finance?
What is diff bet lotus and exchange and which is good in messing only?
How many categories of workes are there in LIC of india?what are they?
you do not have MBA degree. why should we appoint you as Deputy General Manager of CSD Bangladesh?
Hi ,can any one tell me wt 's SOA mean ?
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
Difference between form of a word and its function.
what is marketing, purchase and sale?
Why Amartya sen got Nobel prize? how his theory proved useful for developing nations?
i want to be manager in sotre and purchase
WHAT IS MEANING OF M/S IN RETAIL SENSE ????
can server request to the client:yes/no give the reasion atleast 3
what is GRN ? When to raise GRN?
My technical interview of wipro is on 22 jan.Please send me some questions regarding c & c++.My email address is sjotkaur@gmail.com.