Simplifies the readability of the static method BS
This commit is contained in:
parent
bf79830993
commit
60f6dda70a
@ -17,25 +17,19 @@ class BinarySearch
|
|||||||
* @return the location of the key
|
* @return the location of the key
|
||||||
**/
|
**/
|
||||||
public static int BS(int array[], int key, int lb, int ub)
|
public static int BS(int array[], int key, int lb, int ub)
|
||||||
{ if (lb>ub)
|
{
|
||||||
{
|
if ( lb > ub)
|
||||||
return -1;
|
return -1;
|
||||||
}
|
|
||||||
|
int mid = (lb + ub) / 2;
|
||||||
|
|
||||||
int mid=(lb+ub)/2;
|
if (key < array[mid])
|
||||||
|
|
||||||
if (key<array[mid])
|
|
||||||
{
|
|
||||||
return (BS(array, key, lb, mid-1));
|
return (BS(array, key, lb, mid-1));
|
||||||
}
|
|
||||||
else if (key>array[mid])
|
if (key > array[mid])
|
||||||
{
|
return (BS(array, key, mid + 1, ub));
|
||||||
return (BS(array, key, mid+1, ub));
|
|
||||||
}
|
return mid;
|
||||||
else
|
|
||||||
{
|
|
||||||
return mid;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@ -54,22 +48,21 @@ class BinarySearch
|
|||||||
|
|
||||||
//Input
|
//Input
|
||||||
System.out.println("Enter an array of 10 numbers : ");
|
System.out.println("Enter an array of 10 numbers : ");
|
||||||
for (int i=0; i<10 ;i++ )
|
|
||||||
{
|
for (int i = 0; i < 10 ; i++ )
|
||||||
array[i]=input.nextInt();
|
array[i] = input.nextInt();
|
||||||
}
|
|
||||||
System.out.println("Enter the number to be searched : ");
|
System.out.println("Enter the number to be searched : ");
|
||||||
key=input.nextInt();
|
|
||||||
|
key = input.nextInt();
|
||||||
|
|
||||||
int index=BS(array, key, 0, 9);
|
int index=BS(array, key, 0, 9);
|
||||||
if (index!=-1)
|
|
||||||
{
|
if (index != -1)
|
||||||
System.out.println("Number found at index number : " + index);
|
System.out.println("Number found at index number : " + index);
|
||||||
}
|
else
|
||||||
else
|
|
||||||
{
|
|
||||||
System.out.println("Not found");
|
System.out.println("Not found");
|
||||||
}
|
|
||||||
input.close();
|
input.close();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user