赞
踩
public class Chazhao { public static void main(String[] args) { //二分法查找 注:要求数组必须是有序的 int [] arr= {12,18,18,19,34}; int index =halfSearch(arr,18); System.out.println("索引值是(二分):"+index); //迭代 int[] arr2={1,2,3,4,6,7}; int index2=binarySearch(arr2, 4, 0, arr2.length); System.out.println(); System.out.println("索引值是(迭代):"+index2); //顺序查找 String[] ary = new String []{"aa","bb","cc","dd"}; int k=-1; for( int j=0;j<ary.length;j++) { if(ary[j].equals("bb")){ k=j; System.out.println(); System.out.println("索引值是(顺序):"+k); } } if(k==-1){ System.out.println("您所指定的元素不存在"); } } //二分法调用函数 public static int halfSearch(int [] arr,int i) { int max=arr.length-1; int min=0; int mid=(max+min)/2; int index=-1; while(min<max) { if (i>arr[mid]) { min=mid+1; }else if(i<arr[mid]) { max=mid-1; }else { return mid; } } return index; } //迭代调用方法 public static int binarySearch(int[] arr2,int i,int min,int max){ if(min>max){ return -1; } int mid=(min+max)/2; if(i==arr2[mid]){ return mid; }else if(i>arr2[mid]){ return binarySearch(arr2,i,min+1,max); }else{ return binarySearch(arr2, i, min, mid-1); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。