二分法查找数据首次出现位置

package com.trfizeng.twofenfind;
/**
 * 二分法查找数据
 * 假定num是有序数组
 * @author trfizeng
 *
 */
public class TwoFenFind {
	public static void main(String[] args) {
		int[] num = {0,1,3,5,9,10,30,100,302};
		System.out.println(indexOf(num, 0, num.length - 1,9));
	}
	
	public static int indexOf(int[] num,int L,int R,int key) {
		if (null != num && L <= R && R < num.length) {
			if (L == R - 1) {
				if (key == num[L]) {
					return L;
				}else if(key == num[R]){
					return R;
				}
			}else {
				int mid = (L + R) / 2;
				if (key == num[mid]) {
					return mid;
				}else if(key > num[mid]){
					return indexOf(num, mid + 1, R, key);
				}else{
					return indexOf(num, L, mid, key);
				}
			}
		}
		return -1;
	}
}

  

posted on 2015-03-22 14:04  trfizeng  阅读(311)  评论(0编辑  收藏  举报

导航