本帖最后由 涐扪①起奮乧 于 2013-11-22 00:13 编辑
- class Demo
- {
- public static void main(String[] args)
- {
- int[] arr = {1,2,6,7,15,10,17,12};
- int index1 = getIndex(arr,10);
- System.out.println("index1="+index1);
- bubbleSort(arr);
- printArray(arr);
- int index2 = halfSearch(arr,10);
- System.out.println("index2="+index2);
- }
-
- public static int getIndex(int[] arr,int key)
- {
- for (int x = 0; x<arr.length; x++)
- {
- if(arr[x]==key)
- return x;
- }
- return -1;
- }
-
-
- public static void bubbleSort(int[] arr)
- {
- for (int x = 0; x<arr.length-1; x++)
- {
- for (int y = 0; y<arr.length-x-1; y++)
- {
- if(arr[y]>arr[y+1])
- {
- int temp = arr[y];
- arr[y] = arr[y+1];
- arr[y+1] = temp;
- }
- }
- }
- }
-
- public static void printArray(int[] arr)
- {
- System.out.print("[");
- for (int x = 0; x<arr.length; x++)
- {
- if (x!=arr.length-1)
- System.out.print(arr[x]+",");
- else
- System.out.println(arr[x]+"]");
- }
- }
-
- public static int halfSearch(int[] arr,int key)
- {
- int min,max,mid;
- min = 0;
- max = arr.length-1;
- mid = (min+max)/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 = (min+max)/2;
- }
- return mid;
- }
- }
复制代码 运行结果:
index1=5
[1,2,6,7,10,12,15,17]
index2=4
index1和index2查询的结果不一样,答案应该是5
也没找出来我折半查找算法那个地方错了。。。郁闷中,求解答 |
|