二分查找

package com.test;
/** 
 * @author: Dahai He
 * @time: 2010-5-4 下午01:30:11
 */
public class Search {
	
	public int[] sortArr(int[] arr){
		for(int i = 0; i < arr.length; i++){
			for(int j = 0; j < arr.length - i - 1; j++){
				if(arr[j] > arr[j+1]){
					int temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
		return arr;
	}
	
	public int getIndex(int number, int[] arr, int start, int end){
		if(start > end ){
			return -1;
		}else if(start == end){
			return arr[start] == number ? start : -1;
		}else{
			int currIndex;
			if( (end + 1 - start) % 2 == 0){
				currIndex = (start + end)/2;
			}else{
				currIndex = (start + end)/2 + 1;
			}
			
			int currNumber = arr[currIndex];
			if(currNumber == number){
				return currIndex;
			}else{
				if(currNumber > number){
					return getIndex(number,arr,start,currIndex-1);
				}else{
					return getIndex(number,arr,currIndex+1,end);
				}
			}		
		}	
	}
	
	public static void main(String[] args){
		Search s = new Search();
		int[] arr = {1,8,4,5,7,3,2};
		int[] newArr = s.sortArr(arr);
		for(int i=0;i<newArr.length;i++){
			System.out.print(newArr[i] + ",");
		}
		System.out.println();
		int index = s.getIndex(5, newArr, 0, newArr.length);
		System.out.print(index);
	}
}
 

你可能感兴趣的:(J#)