In Out: Import Public Class Public Static Void Int New

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

import java.util.

Scanner;
public class find
{
public static void main(String args[])
{
int c, first, last, middle, n, find, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
int count = 0;
int count1 = 0;
System.out.println("Enter " + n + " integers");

int i = 0;
boolean found = false;

// set the boolean value to false until the key is found

for (c = 0; c < n; c++)


array[c] = in.nextInt();
System.out.println("Enter value to find");
find = in.nextInt();
for ( i = 0; i < array.length; i++)
{count ++;
if (array[ i ] == find)
{
found = true;
break;
}
}
if (found) //When found is true, the index of the location of key will be printed.
{
System.out.println("Found " + find + " at location " + (i+1) + ".");
System.out.println("The sequantial find found the number after " + count +
" comparisons.\n");
}
else
{
System.out.println(find + " not found in this array.");
}
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < find ){
first = middle + 1;
count1++;
}
else if ( array[middle] == find )

{
count1++;
System.out.println(find + " found at location " + (middle + 1) + ".");
System.out.println("The Binary find find found the number after " + count1 +
" comparisons.");
break;
}

else
last = middle - 1;
count1++;
middle = (first + last)/2;

}
if ( first > last )
{
System.out.println(find + " not found in the array.");
count1++;
}

}
}

You might also like