本帖最后由 pk49800 于 2014-6-8 13:23 编辑
- /**
- * @author Administrator
- * 用折半查找法插入一个元素到一个有序数组并使之有序,返回该元素的位置
- */
- public class HalfSearchTest {
-
- public static int halfSearch(int[] arr, int num){
- int min = 0;int max = arr.length-1; int mid;
- while(min<=max){
- mid = (min+max) >> 1;
- if(num<arr[mid]){
- max = mid - 1;
-
- }else if(num>arr[mid]){
- min = mid + 1;
- }else
- return mid;
-
- }
-
- return min;
-
- }
-
- public static void main(String[] args){
-
- int[] arr ={1,2,3,4,7};
- System.out.print(halfSearch(arr,6));
- }
- }
复制代码
应该是这样的(升序情况) |