---
title: "二分查找"
author: "aiyanbo"
date: "2010-05-13T10:01:40Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-05-13T14:20:11Z"
id: 665353
url: "https://aiy.iteye.com/blog/665353"
---

```
用二分查找方法在一个已经排好序的数组中找出任意一个值的位置比遍历数组效率要高得多，这样子，我们可以只要查找数组的
二之一就可以将值准确地查找出来。

	public int BinSearch(int[] array,int value){
		int startIndex=0;
		int stopIndex=array.length;
		int middleIndex=(int)Math.floor((startIndex+stopIndex)/2);
		while(array[middleIndex]!=value&&startIndex<stopIndex){
			if(value<array[middleIndex])
				stopIndex--;
			if(value>array[middleIndex])
				startIndex++;
			middleIndex=(int)Math.floor((startIndex+stopIndex)/2);
		}
		return (array[middleIndex]==value)?middleIndex:-1;
	}
	public int getLength(String[] array){
		return array==null?-1:array.length;
	}
```