Mercurial > hg > Members > shoshi > AADS
comparison src/search/LinearSearch.java @ 0:a9cb12a7f995
hg init
author | misaka |
---|---|
date | Wed, 06 Jul 2011 15:19:52 +0900 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:a9cb12a7f995 |
---|---|
1 package search; | |
2 | |
3 public class LinearSearch | |
4 { | |
5 public static void main(String args[]) | |
6 { | |
7 LinearSearch table = new LinearSearch(); | |
8 | |
9 table.add(1,"one"); | |
10 table.add(10,"ten"); | |
11 table.add(2,"two"); | |
12 | |
13 String x = (String)table.search(10); | |
14 if(x != null){ | |
15 System.out.println("value = "+x); | |
16 }else{ | |
17 System.out.println("Not found"); | |
18 } | |
19 } | |
20 | |
21 class Entry | |
22 { | |
23 int key; | |
24 Object data; | |
25 | |
26 public Entry(int key,Object data) | |
27 { | |
28 this.key = key; | |
29 this.data = data; | |
30 } | |
31 } | |
32 | |
33 final static int MAX = 100; | |
34 final Entry[] table = new Entry[MAX]; | |
35 int n = 0; | |
36 | |
37 public void add(int key,Object data) | |
38 { | |
39 if(n >= MAX){ | |
40 System.err.println("データの個数が多すぎます。"); | |
41 return; | |
42 } | |
43 | |
44 table[n++] = new Entry(key,data); | |
45 } | |
46 | |
47 public Object search(int key) | |
48 { | |
49 int i; | |
50 | |
51 i = 0; | |
52 while(i < n){ | |
53 if(table[i].key == key){ | |
54 return (table[i].data); | |
55 } | |
56 i++; | |
57 } | |
58 | |
59 return null; | |
60 } | |
61 } |