JAVA Implementation of Binary Search

Source: Internet
Author: User

/* --------------------------------------------------------------- * author: xujin, 4100213 * date: Oct 17, 2012 * binarySearch * to search a number in an array by using binarySearch algorithm * example: binarySearch([1,2,3,4,5,6,7,8], 3, 8) * to produce 2  *---------------------------------------------------------------*/import java.util.Scanner;class BinSearch{public static int binarySearch(int a[], int x, int n){int left = 0;int right = n - 1;while(left <= right){//int middle = (left + right)/2;int middle = left + (right - left)/2;if(x == a[middle]) return middle;if(x > a[middle]) left = middle + 1;else right = middle - 1;}return -1;}} public class xujin_4100213_BinarySearch {static Scanner cin = new Scanner(System.in);public static void main(String[] args){System.out.print("Please input a integer(the size of array): ");int sizeOfArray = cin.nextInt();  int a[] = new int[sizeOfArray];System.out.print("Please input " + sizeOfArray + " sorted numbers: ");for(int i = 0; i < sizeOfArray; i++) a[i] = cin.nextInt();System.out.print("Please input the number you want to search: ");int x = cin.nextInt();   System.out.print("Location: " + BinSearch.binarySearch(a, x, sizeOfArray));}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.