查詢演算法-順序查詢演算法
阿新 • • 發佈:2019-01-14
package com.xj.www.search; import java.util.Scanner; /** * 順序查詢演算法 * * @author xiongjing * */ public class SearchFun { final static int N = 15; // 順序查詢演算法實現 public static int search(int[] a, int n, int x) { int i, f = -1; for (i = 0; i < n; i++) { if (x == a[i]) { f = i; break; } } return f; } // 程式主入口 public static void main(String[] args) { int x, n, i; int[] shuzu = new int[N]; for (i = 0; i < N; i++) { shuzu[i] = (int) (100 + Math.random() * (100 + 1)); } System.out.print("順序查詢演算法演示! \n"); System.out.println("資料序列: \n"); for (i = 0; i < N; i++) { System.out.print(" " + shuzu[i]); } System.out.print("\n\n"); System.out.println("請輸入要查詢的數:"); @SuppressWarnings("resource") Scanner input = new Scanner(System.in); x = input.nextInt(); n = search(shuzu, N, x); if (n < 0) { System.out.println("沒找到資料:" + x); } else { System.out.println("資料:" + x + "位於陣列的第" + (n + 1) + "個元素處。"); } } }