Created
December 21, 2016 18:00
-
-
Save ZaeemSattar/6da0f8c075a3b07703aa57510e68d556 to your computer and use it in GitHub Desktop.
Simplest example of Binary Search in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dorid; | |
public class BinarySearchClass { | |
private static int[] numAarray; | |
private static final int numberToSearch = 89; | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
// array must be sorted | |
numAarray = new int[] { 2, 5, 9, 34, 45, 67, 78, 89, 90 }; | |
int result = BinarySearch(numAarray, 89); | |
if (result == -1) { | |
System.out.println("number not found"); | |
} else { | |
System.out.println("Number is at the index " + result); | |
} | |
} | |
private static int BinarySearch(int[] searchArray, int searchNumeber) { | |
int start, end, mid; | |
start = 0; | |
end = searchArray.length; | |
while (start <= end) { | |
mid = (start + end) / 2; | |
if (searchArray[mid] == searchNumeber) { | |
return mid; | |
} else if (searchNumeber < numAarray[mid]) { | |
end = mid - 1; | |
} else { | |
start = mid + 1; | |
} | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment