本文主要是介绍利用折半查找,寻找元素在数组中合适恰当的位置,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import java.util.Scanner;public class zheBan {public static void main(String args[]) {Scanner input = new Scanner(System.in);//折半查找,前提:数组是有序数组int[] arr = {-12,2,9,11,18,36,54,98,112,365,420,600};System.out.print("原数组:");arrPrint(arr);//动态接收要查找的数字System.out.print("输入要查找位置的数:");int num = input.nextInt();int index = findIndex(arr,num);System.out.println("要查找的数("+num+")在数组中恰当的下标是("+index+")");}// 遍历数组public static void arrPrint(int[] arr) {System.out.print("{");for (int i = 0; i < arr.length; i++) {if (i == arr.length - 1) {System.out.print(arr[i] + "}\n");} else {System.out.print(arr[i] + ",");}}}//查找public static int findIndex(int[] arr, int index){int min = 0;int mid;int max = arr.length - 1;while(min <= max){mid = (min + max) / 2;if(index > arr[mid]){min = mid + 1;}else if(index < arr[mid]){max = mid - 1;}else{return mid;}}return min;}}
这篇关于利用折半查找,寻找元素在数组中合适恰当的位置的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!