package assignment;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
int[] a;
System.out.println("enter the value of n");
Scanner in=new Scanner(System.in);
a=new int[in.nextInt()];
System.out.println("enter the n integers");
for(int i=0;i<a.length;i++){
a[i]=in.nextInt();
}
System.out.println("the sorted array is:");
int temp;
for(int i=0;i<a.length;i++){
for(int j=i+1;j<a.length;j++){
if(a[i]>a[j]){
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println("enter the no to be searched :");
int key=in.nextInt();
int first = 0;
int last = a.length - 1;
int middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < key )
first = middle + 1;
else if ( a[middle] == key )
{
System.out.println(key + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(key + " is not present in the array.\n");
}
}
No comments:
Post a Comment