折半查找,binarySearch

折半查找法也称为二分查找法,它充分利用了元素间的次序关系,采用分治策略,可在最坏的情况下用O(log n)完成搜索任务。它的基本思想是,将n个元素分成个数大致相同的两半,取a[n/2]与欲查找的x作比较,如果x=a[n/2]则找到x,算法终止。如 果x<a[n/2],则我们只要在数组a的左半部继续搜索x(这里假设数组元素呈升序排列)。如果x>a[n/2],则我们只要在数组a的右 半部继续搜索x。

二分查找有个缺点就是元数据必须是有序的,因此二分查找之前必须对对数组排序,可以根据需要选择适当的排序算法这里选择的快速排序算法。

  • 首先设定三个变量,lownum,midnum,hignum 假定有十个元素则lownum = 0,hignum=9,midnum=(lownum+highnum)/2.key为查找数据。
  • 如果a[midnum] = key,表示查找到数据,返回midnum
  • 如果key<a[midnum]则midnum = midnum-1,递归查找a[0] ~ a[midnum-1]
  • 如果key>a[midnum]则midnum = midnum+1,递归查找a[midnum+1] ~a[highnum].

 

 

 

下面看一下java的代码实现

package neuq.chao;
import java.util.Scanner;
class QuickSort{
    static void quickSort(int []a,int left,int right){
        int ltemp,rtemp,base;
        ltemp = left;
        rtemp = right;
        int t;
        base  = a[(right+left)/2];                             //选取中间元素作为边界
        while(ltemp<rtemp){
            while(a[ltemp]<base){
                ++ltemp;                                   //ltemp向右移
            }
            while(a[rtemp]>base){
                --rtemp;                                //rtemp向左移
            }
            if(ltemp<=rtemp){
               t = a[ltemp];
               a[ltemp] = a[rtemp];
               a[rtemp] = t;
               ++ltemp;
               --rtemp;
            }
        }
        if(ltemp==rtemp){
            ltemp++;
        }
        if(left<rtemp){
            quickSort(a,left,ltemp-1);
        }
        if(ltemp<right){
            quickSort(a,rtemp+1,right);
        }
    }
}

public class BinarySearch {                        //折半查找
    static final int SIZE = 10;
    static Scanner input = new Scanner(System.in);
    static int binarySearch(int []a,int left,int right,int key){
        int lownum,midnum,hignum;
        lownum = left;
        midnum = (left+right);
        hignum = right;
        int i =-1;
        if(key==a[midnum]){
            i =  midnum;
        }
        if(key<a[midnum]){
           i =    binarySearch(a,lownum,midnum-1,key);
        }
        if(key>a[midnum]){
            i = binarySearch(a,midnum+1,hignum,key);
        }
        return i;
    }
 public static void main(String args[]){
     int shuzu[] = new int[SIZE];
     int h,j,i,n;
     for(h=0;h<SIZE;h++){
        shuzu[h] = (int)(100+Math.random()*(100+1));
     }
    // QuickSort qs = new QuickSort();
     QuickSort.quickSort(shuzu,0,SIZE-1);
     System.out.print("数组的数据为: \n");
     for(i=0;i<SIZE-1;i++){
         System.out.print(shuzu[i]+" ");
     }
     System.out.print("\n");
     System.out.print("请输入查找的数据: \n");
     n = input.nextInt();
     j = binarySearch(shuzu,0,SIZE-1,n);
     if(j<0){
         System.out.print("未查找到数据");
     }
     else{
         System.out.print(n+"是数组中第"+j+"个数");
     }
 } 
}

 

转载于:https://www.cnblogs.com/code-changeworld/p/4363990.html

A binary search algorithm (or binary chop) is a technique for finding a particular value in a sorted list. It makes progressively better guesses, and closes in on the sought value, by comparing an element halfway with what has been determined to be an element too low in the list and one too high in the list. A binary search finds the median element in a list, compares its value to the one you are searching for, and determines if it’s greater than, less than, or equal to the one you want. A guess that turns out to be too high becomes the new top of the list, and one too low the new bottom of the list. The binary search's next guess is halfway between the new list's top and bottom. Pursuing this strategy iteratively, it narrows the search by a factor 2 each time, and finds your value. A binary search is an example of a divide and conquer algorithm (more specifically a decrease and conquer algorithm) and a dichotomic search (more at Search algorithm). The most common application of binary search is to find a specific value in a sorted list. To cast this in the frame of the guessing game (see Example below), realize that we are now guessing the index, or numbered place, of the value in the list. This is useful because, given the index, other data structures will contain associated information. Suppose a data structure containing the classic collection of name, address, telephone number and so forth has been accumulated, and an array is prepared containing the names, numbered from one to N. A query might be: what is the telephone number for a given name X. To answer this the array would be searched and the index (if any) corresponding to that name determined, whereupon it would be used to report the associated telephone number and so forth. Appropriate provision must be made for the name not being in the list (typically by returning an index value of zero), indeed the question of interest might be only whether X is in the list or not. If the list of names is in sorted order, a binary search will find a given name with far fewer probes than the simple procedure of probing each name in the list, one after the other in a linear search, and the procedure is much simpler than organising a hash table though that would be faster still, typically averaging just over one probe. This applies for a uniform distribution of search items but if it is known that some few items are much more likely to be sought for than the majority then a linear search with the list ordered so that the most popular items are first may do better. The binary search begins by comparing the sought value X to the value in the middle of the list; because the values are sorted, it is clear whether the sought value would belong before or after that middle value, and the search then continues through the correct half in the same way. Only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the differences. Your task is to write a program that, given a set numbers of ascending and a key, finding a particular postion in a sorted list.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值