⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 binarysearch2.java

📁 《算法设计与分析》王晓东编著
💻 JAVA
字号:
import java.util.Scanner;
public class BinarySearch2 {

	public static int binSearch(int[] array,int x){
		int n = array.length;
		int left = 0;int right = n-1;
		while(left<=right)
		{	int middle=(left+right)/2;
			if(x>array[middle]) left=middle+1;
			else if(x<array[middle]) right=middle-1;
			else return middle;
		}
		return -1;
	}
	public static void main(String args[]){
		Scanner in = new Scanner(System.in);
		System.out.print("Please input the length of the array: ");
		int n = in.nextInt();
		int[] array = new int[n];
		System.out.println("Please input the elements in an ascending order:");
		System.out.print("array[0] = ");
		array[0] = in.nextInt();
		for(int i=1;i<n;i++){
				while(true){
				System.out.print("array["+i+"] = ");
				array[i] = in.nextInt();
				if(array[i]>array[i-1]) break;
			}
		}
		System.out.print("To search to position of: ");
		int x = in.nextInt();
		System.out.print("x = array["+binSearch(array,x)+"]");
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -