Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
時代調査
package testprogramm;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Jidai {
public class ClassBinarySearch {
static ClassEra[] data = {
new ClassEra( 0,"原始時代"),
new ClassEra( 593,"飛鳥時代"),
new ClassEra( 710,"奈良時代"),
new ClassEra( 794,"平安時代"),
new ClassEra(1192,"鎌倉時代"),
new ClassEra(1334,"室町時代"),
new ClassEra(1573,"安土桃山時代"),
new ClassEra(1603,"江戸時代"),
new ClassEra(1868,"明治時代"),
new ClassEra(1912,"大正時代"),
new ClassEra(1926,"昭和時代"),
new ClassEra(1989,"平成時代")
};
public static void main(String[] args) {
try{
//キーボードからの入力
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("探索したい年を入力:");
String s = in.readLine();
int y = Integer.parseInt(s);
//探索
s = binarySearch(y);
System.out.println(y + "年は" + s + "です");
}
catch(IOException e) {
System.out.println("IO error");
}
}
/*************************************************
探索
戻り値:時代名を表す文字列
*************************************************/
static String binarySearch(int key) {
//key:探索したい年
String s; //戻り値
if (key < data[1].getYear())
{
s = data[0].getEra();
}
else if (key >= data[data.length-1].getYear())
{
s = data[data.length-1].getEra();
}
else
{
s = search(key,1,data.length-1);
}
return s;
}
/*************************************************
再帰関数
*************************************************/
static String search(int key,int start,int n) {
//key :探索したい値
//start:探索する範囲のはじめの添え字
//n :探索する範囲の個数
int mid; //探索する範囲の中央の添え字
String s; //戻り値
if (n == 2)
{
s = data[start].getEra();
}
else
{
mid = start+n/2;
if (data[mid].getYear() == key)
{
s = data[mid].getEra();
}
else if (data[mid].getYear() < key)
{
//後半を探索
n = start + n - mid; //新しい範囲の個数
s = search(key,mid,n);
}
else
{
//前半を探索
n = mid - start + 1; //新しい範囲の個数
s = search(key,start,n);
}
}
return s;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.