【查找算法之顺序查找算法】

顺序查找:就是从一个集合的第一个元素开始遍历,一直到找到队尾为止,返回查找的下标,因此遍历的结果为:可能找到元素,返回元素下标,可能遍历到队尾仍然找不到元素,返回-1,例如java字符串函数indexOf("d")返回值查不到返回-1;备注:indexOf使用哪种查找算法呢?

package demo.tt;

/**

 * 顺序查找算法

 * @author gaojingsong

 * @email 525354786

 */

public class FindDemo {

/**

* 顺序查找算法演示

* @param args

*/

public static void main(String[] args) {

      FindDemo find = new FindDemo();

       int[] coll = new int[]{1,4,9,3,6,5};

               int num =9;

               int index_location = find.search( coll, num);

               System.out.println(index_location);

        

               int num2 =19;

               index_location = find.search( coll, num2);

               System.out.println(index_location);

}

/**

* 顺序查找算法

* @param collect 需要查找的集合

* @param target  待比较的目标元素

* @return  也许能找到,也许找不到,返回位置

*/

public int search( int[] collect, int target) {

        for ( int i = 0; i < collect. length; i++) {

            if (collect[i] == target) {

               System. out.println( "查到了您想要的结果" + target + ",位置在:" + i);

               return i;

           }

        }

        System.out.println( "sorry!没有查询到您想要的结果!" );

        return -1;

  }

}

猜你喜欢

转载自gaojingsong.iteye.com/blog/2283969