字符串数组的折半查找

折半查找的数组必须是从小到大已排序的数组。

	public static void sort(String[] array ){
		for(int i=0;i

然后对数组进行折半查找

	public static int binaryStringSearch(String[] srcArray,String des){
        int low = 0;   
        int high = srcArray.length-1;   
        while(low <= high) {   
            int middle = (low + high)/2;   
            if(des.equals(srcArray[middle])) {   
                return middle;   
            }else if(des.compareTo(srcArray[middle])<0) {   
                high = middle - 1;   
            }else {   
                low = middle + 1;   
            }  
        }  
        return -1; 
	}

测试用例

	public static void main(String[] args) {
	
	
		String test[] = {"bg","rt","eaa","asf","o","uda","ud"};
		sort(test);
		for(String x:test){
			System.out.println(x);
		}
		
		int p = binaryStringSearch(test,"rt");
		System.out.println(p);
	}

结果

asf
bg
eaa
o
rt
ud
uda
4


你可能感兴趣的:(字符串数组的折半查找)