- ------<a target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------
- //数组的查找练习
- class ArrayTest4
- {
- public static void main(String[] args)
- {
- int[] arr = {3,5,13,15,16,18,55};
- int index = halfSearch_1(arr,18);
- System.out.println(index);
- //把17插入到数组中时,输出它应该所在位置的下标;
- int index2 = getIndex(arr,17);
- System.out.println(index2);
- }
- /*
- 折半查找,提高效率,但是必须是针对有序的数组
- */
- //方法一:
- public static int halfSearch_1(int[] arr,int key)
- {
- //定义三个整型的值,分别表示数组开头元素的下标、
- //中间元素的下标,以及最后元素的下标。
- int min,max,mid;
- min = 0;
- max = arr.length-1;
- mid = (max+min)/2;
- while(arr[mid]!=key)
- {
- if(key>arr[mid])
- min = mid + 1;
- else if(key<arr[mid])
- max = mid - 1;
- if(min>max)
- return -1;
- mid = (max+min)/2;
- }
- return mid;
- }
- //方法二:
- public static int halfSearch_2(int[] arr,int key)
- {
- int min=0,max=arr.length-1,mid;
- while(min<=max)
- {
- mid = (max + min)>>1;
- if(key>arr[mid])
- min = mid + 1;
- else if(key<arr[mid])
- max = mid - 1;
- else
- return mid;
- }
- return -1;
- }
- /*
- 在一个有序的数组中插入一个数,使的插入后这个数组仍然有序,给出插入位置的下标;
- */
- public static int getIndex(int[] arr,int key)
- {
- int min=0,max=arr.length-1,mid;
- while(min<=max)
- {
- mid = (max + min)>>1;
- if(key>arr[mid])
- min = mid + 1;
- else if(key<arr[mid])
- max = mid - 1;
- else
- return mid;
- }
- return min;
- }
- }
复制代码 |
|