From 60f6dda70ac929d9daa27a533479c8604e0646ff Mon Sep 17 00:00:00 2001 From: Matheus Serrao Date: Sun, 16 Jul 2017 04:28:01 -0400 Subject: [PATCH] Simplifies the readability of the static method BS --- Searches/BinarySearch.java | 49 ++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/Searches/BinarySearch.java b/Searches/BinarySearch.java index 54f2c4c8..e665dadd 100644 --- a/Searches/BinarySearch.java +++ b/Searches/BinarySearch.java @@ -17,25 +17,19 @@ class BinarySearch * @return the location of the key **/ public static int BS(int array[], int key, int lb, int ub) - { if (lb>ub) - { + { + if ( lb > ub) return -1; - } + + int mid = (lb + ub) / 2; - int mid=(lb+ub)/2; - - if (keyarray[mid]) - { - return (BS(array, key, mid+1, ub)); - } - else - { - return mid; - } + + if (key > array[mid]) + return (BS(array, key, mid + 1, ub)); + + return mid; } @@ -54,22 +48,21 @@ class BinarySearch //Input System.out.println("Enter an array of 10 numbers : "); - for (int i=0; i<10 ;i++ ) - { - array[i]=input.nextInt(); - } + + for (int i = 0; i < 10 ; i++ ) + array[i] = input.nextInt(); + System.out.println("Enter the number to be searched : "); - key=input.nextInt(); + + key = input.nextInt(); int index=BS(array, key, 0, 9); - if (index!=-1) - { - System.out.println("Number found at index number : " + index); - } - else - { + + if (index != -1) + System.out.println("Number found at index number : " + index); + else System.out.println("Not found"); - } + input.close(); } }