---
title: "二分查找"
author: "背着家走"
date: "2013-01-10T12:00:14Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2016-11-30T15:18:50Z"
id: 1767366
url: "https://mumaqm.iteye.com/blog/1767366"
---

二分查找 


```java

/**
	 * 从中查找的数组  n 目标元素
	 * 返回要查找元素在数组中的位置
	 * 如果没找到 返回 -1 
	 * @param intArray 源数组
	 * @param n        目标元素
	 * @return         返回元素在数组中的位置 从0 开始
	 * */
	public static int search(int[] intArray,int n){
		int startPos = 0;
		int endPos = intArray.length - 1;
		int midPos = (startPos + endPos)/2;
		
		if (intArray.length <= 0){
			return - 1;
		}
		
		while(startPos <= endPos){
			if(intArray[midpos] ==  n){
				return midPos ;
			}else if(n >  intArray[midpos]){
				startPos = midPos + 1 ;
				midPos = (startPos + endPos)/2;
			}else{
				endPos = midPos - 1;
				midPos = (startPos + endPos)/2;
			}
		}
		return -1;
	}



```