- import java.util.Scanner;
- import java.io.*;
- class test
- {
- public static void main(String[] args)
- {
- int i,j,temp;
- int n;
- int a[]=new int[10]; //创建数组
- int low=0,high=10,mid;
- Scanner in=new Scanner(System.in);
- System.out.println("input the array:");
- for(i=0;i<10;i++)
- {
- a[i]=in.nextInt();;
- }
- for(i=0;i<10;i++) /* 冒泡排序 */
- for(j=0;j<10-i-1;j++)
- {
- if(a[j]>a[j+1])
- {
- temp=a[j];
- a[j]=a[j+1];
- a[j+1]=temp;
- }
- }
- System.out.println("after sort,the array:");
- for(i=0;i<10;i++)
- System.out.print(a[i]+" ");
- System.out.println("input a data n:");
- n=in.nextInt();
- while(low<=high) /*折半查找*/
- {
- mid=(low+high)/2;
- if(n==a[mid])
- {
- System.out.println("the data is in:"+mid);
- break;
- }
- else if(n<a[mid])
- high=mid-1;
- else if(n>a[mid])
- low=mid+1;
- }
- }
- }
复制代码 |