Created
January 16, 2017 12:30
-
-
Save mokomokohitsuzi/62c8abf9f80585a02ebde13729599a57 to your computer and use it in GitHub Desktop.
新・明解Java入門 演習7-17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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