首页 > 编程语言 > 详细

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

时间:2016-03-18 02:11:02      阅读:186      评论:0      收藏:0      [点我收藏+]

顺序查找:就是从一个集合的第一个元素开始遍历,一直到找到队尾为止,返回查找的下标,因此遍历的结果为:可能找到元素,返回元素下标,可能遍历到队尾仍然找不到元素,返回-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;

? }

}

?

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

原文:http://gaojingsong.iteye.com/blog/2283969

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!