Created
August 14, 2016 08:59
-
-
Save sbsatter/3563a0ac63bf32534bcfdb7d7a281296 to your computer and use it in GitHub Desktop.
Binary Search in java. Add array as a series of arguments, reserving the last argument for the element to find.
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
import java.util.Arrays; | |
class BinarySearch{ | |
public static void main(String ... args){ | |
int [] array; | |
if(args.length!=0){ | |
array= new int [args.length-1]; | |
for(int i=0; i<args.length-1; i++){ | |
array[i]=Integer.parseInt(args[i]); | |
} | |
Arrays.sort(array); | |
binarySearch(array, Integer.parseInt(args[args.length-1])); | |
} | |
} | |
public static int binarySearch(int [] arr, int x){ | |
int first=0, last= arr.length-1, pass=01; | |
boolean found= false; | |
int middle=-1; | |
while(!found && first<=last){ | |
System.out.print("Pass "+pass+": "); | |
middle= (first+last)/2; | |
if(x>arr[middle]){ | |
first=middle+1; | |
}else if(x<arr[middle]){ | |
last= middle-1; | |
}else if(x == arr[middle]){ | |
found=true; | |
} | |
for(int i=first; i<=last; i++){ | |
System.out.print(arr[i]+" "); | |
} | |
System.out.println(); | |
pass++; | |
} | |
if(found){ | |
System.out.println("Found at index "+middle); | |
return middle; | |
} | |
System.out.println("Not found"); | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment