In: Computer Science
Implement a method that meets the following requirements:
(a) Has the same requirements as the above method, but works with
an int array that is sorted in increasing order. Attempt your best
complexity
(b) In comments above the method, explain what its algorithmic
complexity is and why (constant, logarithmic, linear,
quadratic...)
CODE IN JAVA:
public class Search {
//the time complexity of this method is
logarthmic
public static void binarySearch(int[] arr, int num)
{
int beg = 0 ;
int end = arr.length - 1 ;
boolean flag = true;
int ind = -1;
while(beg<=end) {
int mid =
(beg+end)/2;
if(arr[mid]==num) {
flag = false;
System.out.println("Your number is found at the
index "+mid);
break;
}
else
if(arr[mid]>num)
end = mid - 1 ;
else
beg = mid + 1 ;
}
if(flag)
System.out.println("Your number is found at the index...");
}
public static void main(String[] args) {
// TODO Auto-generated method
stub
int arr[] =
{1,2,3,4,5,6,7,8,9,10};
int num = 10;
System.out.println("The array
is:");
for(int
i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println("\nThe number to
be searched is:"+num);
binarySearch(arr,num);
}
}
OUTPUT: