静态查找设置哨兵,可以减少比较次数,效率会有所提高。静态查找算法简单,效率较低
1 package com.gxf.search; 2 3 /** 4 * 静态查找实现 5 * @author xiangfei 6 * 7 */ 8 public class StaticSearch { 9 10 public int search(int array[], int k){ 11 array[0] = k;//设置哨兵 12 int index = array.length - 1; 13 14 for(; index >= 0;index--){ 15 if(array[index] == k) 16 break; 17 } 18 return index; 19 } 20 /** 21 * 测试 22 * @param args 23 */ 24 public static void main(String args[]){ 25 int array[] = {0,3,7,9,30,25}; 26 StaticSearch search = new StaticSearch(); 27 28 for(int i = 1; i < array.length; i++){ 29 System.out.print(array[i] + " "); 30 } 31 System.out.println(); 32 int elementToSear = 7; 33 int index = search.search(array, elementToSear); 34 if(index <= 0){ 35 System.out.println(elementToSear + "不在数组中!"); 36 } 37 else{ 38 System.out.println(elementToSear + "在数组中的位置:" + index); 39 } 40 } 41 }
执行结果
3 7 9 30 25
7在数组中的位置:2