循序搜尋(Sequential Search)是最基礎的搜尋演算法:從陣列首部開始,依序比對每個元素,找到目標值即提前結束,否則遍歷至陣列末尾。
原始資料:int[] a = {4, 6, 2, 8, 1, 9, 0, 3},搜尋目標:8。程式會依序比對索引 0 至 3,於索引 3 找到目標值並回傳位置。
import java.util.Scanner;
public class SequentialSearch {
public static void main(String[] args) {
int[] data = {4, 6, 2, 8, 1, 9, 0, 3};
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入要搜尋的數字:");
int target = scanner.nextInt();
int position = search(data, target);
if (position == -1) {
System.out.println("陣列中不存在該數字。");
} else {
System.out.printf("找到數字,位於陣列第 %d 個位置(索引 %d)。%n", position + 1, position);
}
}
/** 循序搜尋核心邏輯 */
public static int search(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i; // 回傳索引
}
}
return -1; // 未找到
}
}
程式會提示使用者輸入數字,呼叫 search() 方法搜尋,並根據回傳值輸出結果。若輸入 8,將顯示「找到數字,位於陣列第 4 個位置(索引 3)」。