Program To Demonstrate How To Do Binary Search In Java

package com.hubberspot.binarysearch.example; import java.util.Scanner;

package com.hubberspot.binarysearch.example;

import java.util.Scanner;

public class BinarySearch {
public static void main(String[] args){
int[] numbers = {3, 4, 5, 6, 7, 2, -3, 4, 16, 14};
sort(numbers);

Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number you want to "
+ "search from array : ");

int key = scanner.nextInt();

boolean position = binarySearch(numbers,key);

if(position == true)
System.out.println("Array contain the element to "
+ "be searched");
else
System.out.println("Array does not contain the element"
+ " to be searched");
}

public static void sort(int[] list) {
boolean nextPass = true;

for (int k = 1; k < list.length

&& nextPass; k++) {
nextPass = false;
for (int i = 0; i < list.length - k; i++) {
if (list[i] > list[i + 1]) {

int temp = list[i];
list[i] = list[i +

1];
list[i + 1] = temp;

nextPass = true;
}
}
}
}

public static boolean binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;

while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return true;
else
low = mid + 1;
}

return false;
}
}


For more of such hot topics read my other posts here :

Visit my new website



Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 152 0

Please login to comment on this post.
There are no comments yet.
How To Pass Input From A Console To A Java Program ?.
Program To Demonstrate The Use Of Abstract Class And Methods In Java