Java經(jīng)典算法匯總之順序查找(Sequential Search)
更新時間:2016年04月23日 12:00:36 作者:神話丿小王子
Java查找算法之順序查找說明:順序查找適合于存儲結(jié)構(gòu)為順序存儲或鏈接存儲的線性表。 下面我們來詳細說明下
a)原理:順序查找就是按順序從頭到尾依次往下查找,找到數(shù)據(jù),則提前結(jié)束查找,找不到便一直查找下去,直到數(shù)據(jù)最后一位。
b)圖例說明: 原始數(shù)據(jù):int[]a={4,6,2,8,1,9,0,3}; 要查找數(shù)字:8

找到數(shù)組中存在數(shù)據(jù)8,返回位置。
代碼演示:
import java.util.Scanner;
/*
* 順序查找
*/
public class SequelSearch {
public static void main(String[] arg) {
int[] a={4,6,2,8,1,9,0,3};
Scanner input=new Scanner(System.in);
System.out.println("請輸入你要查找的數(shù):");
//存放控制臺輸入的語句
int num=input.nextInt();
//調(diào)用searc()方法,將返回值保存在result中
int result=search(a, num);
if(result==-1){
System.out.println("你輸入的數(shù)不存在與數(shù)組中。");
}
else
System.out.println("你輸入的數(shù)字存在,在數(shù)組中的位置是第:"+(result+1)+"個");
}
//順序排序算法
public static int search(int[] a, int num) {
for(int i = 0; i < a.length; i++) {
if(a[i] == num){//如果數(shù)據(jù)存在
return i;//返回數(shù)據(jù)所在的下標,也就是位置
}
}
return -1;//不存在的話返回-1
}
}
運行截圖:

您可能感興趣的文章:

