javaのリニアサーチ。これは書籍のほぼ丸写し。
import java.util.*; import java.io.BufferedReader; public class LinearSearch { private static int linearSearch(int x, int[] a) { int n = 0; while (n < a.length) { if (a[n] == x) { return n; } n++; } return -1; } public static void main(String[] args) { int [] array = new int[20]; Random random = new Random(); for (int i = 0; i < array.length; ++i) { array[i] = random.nextInt(10); System.out.println(array[i] + ""); } System.out.println("\n What is searching for?"); int x = intReader(); int r = linearSearch(x, array); if (r == -1) { System.out.println("Could not find anything that matches the " + x); } else { System.out.println(x + " is found at " + r); } } private static int intReader() { try { BufferedReader read = new BufferedReader(new java.io.InputStreamReader(System.in)); String str = read.readLine(); return Integer.parseInt(str); } catch (java.io.IOException e) { System.err.println("IO Exception"); return 0; } catch (NumberFormatException e) { return 0; } } }
ruby版リニアサーチ。
# -*- coding: utf-8 -*- def linear_search(numbers, target) i = 1 # リニアサーチの実行。対象が見つかった場合にはそのインデックスを返す numbers.each do |number| if number == target.to_i return i end i = i + 1 end # 見つからない場合には-1を返す return -1 end # 乱数を格納する配列を生成 numbers = [] 20.times { numbers << rand(100) } # 配列の出力 j = 0 numbers.each do |number| puts "#{j} : #{number}" j = j + 1 end # 検索対象の問いかけ puts "What is searching for?" # コマンドラインからの入力の受け取り target = STDIN.gets target = target.chomp # リニアサーチの実行 search_result = linear_search(numbers, target) # 検索結果の出力 if search_result == -1 puts "Could not found anything that matches \"#{target}\"" else puts "#{target} is found at #{search_result}" end