代码改变世界

Java数组2(2015-8-27)

2015-08-27 13:39  马尔代夫_珍  阅读(163)  评论(0编辑  收藏  举报

1、二分查找法讲解:如果使用二分查找法做操作的话,数组必须为有序的。 所以一开始是无序数组时,要先排序为有序数组。 

public class Test2{

 public static void main(String[] args){  

 //--查找某个数据,所在的位置  

              int number = 8;  

 //--定义个数组  

 //int[] arr = new int[]{7,2,10,9,45,3,4};

//排序和二分法同时使用。    

               int[] arr = new int[]{2,3,4,7,9,10,45};   

//--开始下标  

              int start = 0;   

//--终止下标   

              int end = arr.length-1;  

 //--所求出的中间下标  

              int middle;  

 //--存储数组所在位置的容器(如果最后打印出index为-1,证明查找的数据不存在)  

             int index = -1;   

             while(start<=end){      

                      middle = (start+end)/2;   

                      if(number==arr[middle]){    

                                index = middle+1;    

                                break;  

                      }else if(number<arr[middle]){   

                               end = middle -1;    

                     }else if(number>arr[middle]){   

                               start = middle +1;    

                     }

           }  

          if(index==-1){    

                          System.out.println("没找到所需要的数据!!!");   

         }else{   

                         System.out.println("数据的位置为:"+index);   

         }     

 } }

2、import java.util.Scanner;

public class BinarySearch{      

  public static void main(String [] args){              

        int [] array={10,20,30,40,50,60,70,80};           

System.out.println("请输入要查找的数:");           

Scanner input=new Scanner(System.in);         

   int number=input.nextInt();          

  int index=-1;          

  int start=0;         

   int end=array.length-1;       

     int middle;       

     while(start<=end){              

                 middle=(start+end)/2;                

                  if(number==array[middle]){                      

                                            index=middle+1;                       

                                           break;               

                 }              

                 if(number>array[middle]){                        

                                    start=middle+1;                  

                  }              

               if(number<array[middle]){                      

                                        end=middle-1;            

               }           

       }

           if(index==-1){                   

                       System.out.println("没找到");          

          }else{                 

                     System.out.println("找到了"+index);         

   } }}