Binary Search Using Java

 package sorting;


import java.util.Arrays;


public class BinarySearch {


public static void main(String[] args) {

int arr[] = { 1, 34, 4, 5, 7, 8, 9, 11, 3, 55, 67 };

int num = 3;

int found = 0;

boolean flag = false;

int j = 0, k = 0;

Arrays.sort(arr);

int mid = arr[arr.length / 2];

if (num == mid) {

System.out.println("Found the number " + mid);


} else {

if (num < mid) {

j = 0;

k = arr.length / 2;

} else {

j = arr.length / 2;

k = arr.length;

}


for (int i = j; i < k; i++) {

if (arr[i] == num) {

found = arr[i];

flag = true;

}

}

if (flag) {

System.out.println("Number found:: " + found);

} else {

System.out.println("Number not found:: " + num);


}

}


}


}


Comments

Popular posts from this blog

3 Lines of Code And You Can Download Your Favourite Youtube Video.

Leetcode Problem(Easy) Roman to Integer

Leetcode : (Find Minimum in Rotated Sorted Array)