Skip to content

Commit 0d10529

Browse files
Merge pull request #71 from BluurProgrammer/improve_static_method_bs
Simplifies the readability of the static method BS
2 parents bf79830 + 60f6dda commit 0d10529

File tree

1 file changed

+21
-28
lines changed

1 file changed

+21
-28
lines changed

Searches/BinarySearch.java

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,19 @@ class BinarySearch
1717
* @return the location of the key
1818
**/
1919
public static int BS(int array[], int key, int lb, int ub)
20-
{ if (lb>ub)
21-
{
20+
{
21+
if ( lb > ub)
2222
return -1;
23-
}
23+
24+
int mid = (lb + ub) / 2;
2425

25-
int mid=(lb+ub)/2;
26-
27-
if (key<array[mid])
28-
{
26+
if (key < array[mid])
2927
return (BS(array, key, lb, mid-1));
30-
}
31-
else if (key>array[mid])
32-
{
33-
return (BS(array, key, mid+1, ub));
34-
}
35-
else
36-
{
37-
return mid;
38-
}
28+
29+
if (key > array[mid])
30+
return (BS(array, key, mid + 1, ub));
31+
32+
return mid;
3933
}
4034

4135

@@ -54,22 +48,21 @@ public static void main(String[] args)
5448

5549
//Input
5650
System.out.println("Enter an array of 10 numbers : ");
57-
for (int i=0; i<10 ;i++ )
58-
{
59-
array[i]=input.nextInt();
60-
}
51+
52+
for (int i = 0; i < 10 ; i++ )
53+
array[i] = input.nextInt();
54+
6155
System.out.println("Enter the number to be searched : ");
62-
key=input.nextInt();
56+
57+
key = input.nextInt();
6358

6459
int index=BS(array, key, 0, 9);
65-
if (index!=-1)
66-
{
67-
System.out.println("Number found at index number : " + index);
68-
}
69-
else
70-
{
60+
61+
if (index != -1)
62+
System.out.println("Number found at index number : " + index);
63+
else
7164
System.out.println("Not found");
72-
}
65+
7366
input.close();
7467
}
7568
}

0 commit comments

Comments
 (0)