码迷,mamicode.com
首页 > 编程语言 > 详细

java数据结构和算法------哈希查找

时间:2015-07-07 10:48:57      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

 1 package iYou.neugle.search;
 2 
 3 public class Hash_search {
 4     private static int m = 13;
 5     private static int[] hash = new int[m];
 6     private static int[] array = new int[] { 13, 25, 2, 60, 39, 52 };
 7 
 8     public static void main(String[] args) {
 9         InsertHash();
10         System.out.println("哈希表建立如下:");
11         System.out.print("[");
12         for (int i = 0; i < hash.length; i++) {
13             System.out.print(hash[i]);
14             if (i != hash.length - 1) {
15                 System.out.print(",");
16             }
17         }
18         System.out.println("]");
19         System.out.println("39在哈希表中的位置为:" + SearchHash(39));
20     }
21 
22     public static void InsertHash() {
23         // 除法取余法
24         for (int i = 0; i < array.length; i++) {
25             int value = array[i];
26             int address = value % m;
27             while (hash[address] != 0) {
28                 address = (++address) % m;
29             }
30             hash[address] = value;
31         }
32     }
33 
34     public static int SearchHash(int key) {
35         // 开放地址法
36         int address = key % m;
37         while (hash[address] != 0 && hash[address] != key) {
38             address = (++address) % m;
39         }
40 
41         if (hash[address] == 0) {
42             return -1;
43         }
44         return address;
45     }
46 }

 

java数据结构和算法------哈希查找

标签:

原文地址:http://www.cnblogs.com/niuxiaoha/p/4626096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!