码迷,mamicode.com
首页 > 编程语言 > 详细

Java数组2(2015-8-27)

时间:2015-08-27 14:50:20      阅读:153      评论:0      收藏: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);         

   } }}

Java数组2(2015-8-27)

标签:

原文地址:http://www.cnblogs.com/Ly426/p/4763058.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!