把我做练习的一个简单的代码给你看看,希望对你有帮助
- <P><FONT style="BACKGROUND-COLOR: #ffffff">class erfen
- {
- public static void main(String[] args)
- {
- int[] arr={1,2,3,5,6,7,9};
- System.out.print("当前数组为:");
- printArray(arr);//输出数组
- int index = halfSort(arr,6);
- System.out.println("所查询数组元素为:arr["+index+"]");
- }</FONT></P>
- <P><FONT style="BACKGROUND-COLOR: #ffffff"> 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]+"] ");
- }
- }</FONT></P>
- <P><FONT style="BACKGROUND-COLOR: #ffffff">
-
- public static int halfSort(int[] arr,int key)
- {
- int 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;
- }
- }</FONT></P>
复制代码 |