/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myjava;
import java.util.Scanner;
/**
*
* @author Administrator
*/
public class SearchArray {
public static void BinarySearch(int[] arr,int temp){
int high,low,mid;
high = arr.length-1;
low = 0;
mid = (high + low)/2;
while (high >= low){
if (temp == arr[mid]){
System.out.println("We found the number:" +temp +",position:"+(mid+1));
break;
}
else if (temp < arr[mid]){
high = mid -1;
}
else if (temp > arr[mid]){
low = mid +1;
}
if (high < low)
{
System.out.println("Sorry,We didn't found the number:" +temp );
break;
}
mid = (high + low)/2;
}
}
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6,7};
for (int i = 0;i<arr.length;i++ ){
System.out.printf(arr[i] + " ");
}
System.out.println();
while(1<2){
System.out.println("Please input the number you want to search: ");
Scanner intScanner = new Scanner(System.in);
int temp = intScanner.nextInt();
BinarySearch(arr,temp);
}
}
}
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myjava;
import java.util.Scanner;
/**
*
* @author Administrator
*/
public class SearchArray {
public static void BinarySearch(int[] arr,int temp){
int high,low,mid;
high = arr.length-1;
low = 0;
mid = (high + low)/2;
while (high >= low){
if (temp == arr[mid]){
System.out.println("We found the number:" +temp +",position:"+(mid+1));
break;
}
else if (temp < arr[mid]){
high = mid -1;
}
else if (temp > arr[mid]){
low = mid +1;
}
if (high < low)
{
System.out.println("Sorry,We didn't found the number:" +temp );
break;
}
mid = (high + low)/2;
}
}
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6,7};
for (int i = 0;i<arr.length;i++ ){
System.out.printf(arr[i] + " ");
}
System.out.println();
while(1<2){
System.out.println("Please input the number you want to search: ");
Scanner intScanner = new Scanner(System.in);
int temp = intScanner.nextInt();
BinarySearch(arr,temp);
}
}
}