Skip to content

Instantly share code, notes, and snippets.

@mokomokohitsuzi
Created January 16, 2017 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mokomokohitsuzi/62c8abf9f80585a02ebde13729599a57 to your computer and use it in GitHub Desktop.
Save mokomokohitsuzi/62c8abf9f80585a02ebde13729599a57 to your computer and use it in GitHub Desktop.
新・明解Java入門 演習7-17
import java.util.Scanner;
public class En07_17 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.print("要素数:");
int num = stdIn.nextInt();
int[] x = new int[num];
// 要素数numの配列を作成
for (int i = 0; i < x.length; i++) {
System.out.print("x[" + i + "]:");
x[i] = stdIn.nextInt();
}
System.out.println();
System.out.print("探す値:");
int ky = stdIn.nextInt();
// メソッド実行
int idx = linearSearchR(x, ky);
// 結果を表示
if (idx == -1) {
System.out.println("その値の要素は存在しません");
} else {
System.out.printf("その値はx[%d]にあります。\n", idx);
}
}
static int linearSearchR(int[] a, int key) {
// 配列aを逆から走査する。
for (int i = a.length; i > 0; i--) {
if (a[i - 1] == key) {
// 見つかったらインデックスを返却する
return i - 1;
}
}
// 探索失敗は-1を返却
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment