---
title: "二分（折半）查找算法"
author: "ArronZhen"
date: "2012-10-29T08:43:52Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-10-29T08:43:52Z"
id: 1707074
url: "https://arronzhen.iteye.com/blog/1707074"
---

### [二分（折半）查找算法](http://128kj.iteye.com/blog/1678956)

- **博客分类：**
- [查找](http://128kj.iteye.com/category/248049)

[java](http://www.iteye.com/blogs/tag/java) [算法](http://www.iteye.com/blogs/tag/%E7%AE%97%E6%B3%95) [数据结构](http://www.iteye.com/blogs/tag/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84)

二分查找又称折半查找，它是一种效率较高的查找方法。

  折半查找的算法思想是将数列按有序化(递增或递减)排列，查找过程中采用跳跃式方式查找，即先以有序数列的中点位置为比较对象，如果要找的元素值小于该中 点元素，则将待查序列缩小为左半部分，否则为右半部分。通过一次比较，将查找区间缩小一半。 折半查找是一种高效的查找方法。它可以明显减少比较次数，提高查找效率。但是，折半查找的先决条件是查找表中的数据元素必须有序。

  折半查找法的优点是比较次数少，查找速度快，平均性能好;其缺点是要求待查表为有序表，且插入删除困难。因此，折半查找方法适用于不经常变动而查找频繁的有序列表。

算法步骤描述  
① 首先确定整个查找区间的中间位置 mid = （ low + high ）/ 2

② 用待查关键字值与中间位置的关键字值进行比较；

　 若相等，则查找成功

　 若大于，则在后（右）半个区域继续进行折半查找

　 若小于，则在前（左）半个区域继续进行折半查找

③ 对确定的缩小区域再按折半公式，重复上述步骤。

最后，得到结果：要么查找成功， 要么查找失败。折半查找的存储结构采用一维数组存放。

Java代码  [![收藏代码](http://128kj.iteye.com/images/icon_star.png)]()

01. public   class  Test{
02. public   static  &lt; T   extends  Comparable &lt; ?  super  T&gt;&gt;  int  binarySearch(T \[] array,T key){
03. int  low =  0 ;
04. int  high = array.length- 1 ;
05. while (low &lt;= high){
06. int  mid = (low + high)/ 2 ;
07. if (array\[mid].compareTo(key)&lt;  0 ){
08. low = mid + 1 ;
09. }else   if (array\[mid].compareTo(key)&gt; 0 ){
10. high = mid - 1 ;
11. }else {
12. return  mid;
13. }
14. }
15. return  - 1 ;
16. }
17. public   static   void  main(String args\[]){
18. Integer  a\[]={1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };
19. int  k=binarySearch(a, 7 );
20. System.out.println("k=" +k);
21. }
22. }