Anda di halaman 1dari 2

import java.util.

Scanner;
public class BinarySequentialSearch
{
static Scanner console = new Scanner (System.in);
public static void main(String[ ] args)

{
int num,c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
array = new int[20];
System.out.print("Enter 20 integers : ");
for (c = 0; c < array.length; c++)
array[c] = in.nextInt();

for (int j = 0; j < 10; j++)


{
System.out.print("\n"+"Key in the search key : ");
int key = in.nextInt();

System.out.println("\n"+"Sequential Search : ");

int i = 0;
boolean found = false;

for ( i = 0; i < array.length; i++)


{
if (array[ i ] == key)
{
found = true;
break;
}
}

if (found)
{
int loc = i + 1;
System.out.println("\n"+"\t"+"Status"+"\t"+"\t"+": "+"Success");
System.out.println("\t"+"Found " + " at index : " + i +"");
System.out.println("\t"+"Number of comparison : " + loc +"\n");
}

else
{
System.out.println("\n"+"\t"+"Fail. "+ key + " is not in this
array."+"\n");
}

System.out.println("\n"+"Binary Search : ");

first = 0;
last = array.length - 1;
middle = (first + last)/2;

int count = 0;
while(first <= last)
{

if ( array[middle] < key )


{
first = middle + 1;
count = 2 + count;
}

else if ( array[middle] == key )


{

System.out.println("\n"+"\t"+"Status"+"\t"+"\t"+": "+"Success");
System.out.println("\t"+"Found " + " at index : " +
(middle));
System.out.println("\t"+"Number of comparison : " + (count
+ 1) +"\n");
System.out.println("\n"+"Conclusion : Binary search is the better and easy than
Sequential Search."+"");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;

}
if ( first > last )

System.out.println("\n"+"\t"+"Fail. "+key + " is not have in the


list.\n"+"\n");

}
}
}

Anda mungkin juga menyukai