Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by MOHIT on 10-03-2017.
- */
- import java.util.Scanner;
- public class search {
- // static array to store elements
- static int element[];
- public static void main(String arg[]) {
- Scanner sc = new Scanner(System.in);
- // the following block takes comma seperated inputs and puts them into array
- System.out.println("Enter the elements of the array : ");
- String nums = sc.next();
- String[] strArr = nums.split(",");
- int size = strArr.length;
- element = new int[size];
- int i = 0;
- for (String str2 :strArr) {
- int temp = Integer.parseInt(str2);
- element[i] = temp;
- i++;
- }
- // binary search requires the array to be sorted
- // call to the sorting function
- bubbleSort();
- // enter the number to be searched
- System.out.println("\nEnter the number to be searched : ");
- int num = sc.nextInt();
- // check if position is >= 0 then the element is found
- int position = binarySearch(num);
- if (position >= 0) {
- System.out.println("Element found at position " + position);
- } else {
- System.out.println("Element not found in the array");
- }
- }
- // method that sorts the array using the bubble Sort algorithm
- static void bubbleSort() {
- int n = element.length;
- for (int i = 0; i < n - 1; i++) {
- for (int j = 0; j < n - 1; j++) {
- if (element[j] > element[j + 1]) {
- int temp = element[j];
- element[j] = element[j + 1];
- element[j + 1] = temp;
- }
- }
- }
- System.out.println("The sorted Array is : ");
- for (int k:element) {
- System.out.print(k + " ");
- }
- return;
- }
- // method to search element using binary search algorithm
- static int binarySearch(int num) {
- int low = 0, high = element.length - 1;
- boolean found = false;
- int position = 0;
- // loop till high is greater than low or till the element is not found
- while (low <= high && found == false) {
- // calculate the mid value
- int mid = (low + high) / 2;
- // compare the mid value with the element
- // if equal then print the position and return
- if (element[mid] == num) {
- position = mid;
- found = true;
- break;
- }
- // else if the middle value if greater than the element
- // then element lies on the left side of the mid so decrease high value
- else if (element[mid] > num) {
- high = mid - 1;
- }
- // else if the middle value if less than the element
- // then element lies on the right side of the mid so increase low value
- else if (element[mid] < num) {
- low = mid + 1;
- }
- }
- // display this if element not found
- if (found == false) {
- return -1;
- }
- return position + 1;
- }
- }
Add Comment
Please, Sign In to add comment