如何使用java實現Open Addressing

你好! 我們這裏總共向您提供三種open addression的方法,分別爲linear probing、quadratic probing和double hashing。

Linear Probing

Linear probing是計算機程序解決散列表衝突時所採取的一種策略。散列表這種數據結構用於保存鍵值對,並且能通過給出的鍵來查找表中對應的值。Linear probing這種策略是在1954年由Gene Amdahl, Elaine M. McGraw,和 Arthur Samuel 所發明,並且最早於1963年由Donald Knuth對其進行分析。

  1. 假設A是哈希表的一個容量N爲15的數組;
  2. 將Keys(5、9、12、24、31、40、47、53、62、71)使用linear probing按照順序依次插入到數組中。

public static void main(String[] args) {
int N = 15;
int[] A = new int [N];
int[] Keys = {5, 9, 12, 24, 31, 40, 47, 53, 62, 71};
for (int i = 0; i < Keys.length; i++) {
        int j = 0;
        int Position = Keys[i] % N;
        while (A[Position] != 0) {
            j = j + 1;
            Position = Keys[i] % N + j;
        }
        A[Position] = Keys[i];          
    }
for (int i = 0; i < A.length; i++) {
        System.out.println(A[i]);
    }       
}

Quadratic Probing

Quadratic probing是計算機程序解決散列表衝突時所採取的另一種策略,用於解決散列表中的衝突。Quadratic probing通過獲取原始哈希索引並將任意二次多項式的連續值相加,直到找到一個空槽來進行操作。

  1. 假設A是哈希表的一個容量N爲15的數組;
  2. 將Keys(5、9、12、24、31、40、47、53、62、71)使用quadratic probing按照順序依次插入到數組中。

public static void main(String[] args) {
int N = 15;
int[] A = new int [N];
int[] Keys = {5, 9, 12, 24, 31, 40, 47, 53, 62, 71};
for (int i = 0; i < Keys.length; i++) {
        int j = 0;
        int Position = Keys[i] % N;
        while (A[Position] != 0) {
            j = j + 1;
            Position = (Keys[i] % N + j*j) % N;
        }
        A[Position] = Keys[i];          
    }
for (int i = 0; i < A.length; i++) {
        System.out.println(A[i]);
    }   
}

Double Hashing

Double hashing是計算機程序解決散列表衝突時所採取的另一種策略,與散列表中的開放尋址結合使用,通過使用密鑰的輔助哈希作爲衝突發生時的偏移來解決哈希衝突。具有open addressing的double hashing是表上的經典數據結構。

  1. 假設A是哈希表的一個容量N爲15的數組;
  2. 將Keys(5、9、12、24、31、40、47、53、62、71)使用double hashing(我們假設h’(k)爲13 – (k mod 13))按照順序依次插入到數組中。

public static void main(String[] args) {
int N = 15;
int[] A = new int [N];
int[] Keys = {5, 9, 12, 24, 31, 40, 47, 53, 62, 71};    
for (int i = 0; i < Keys.length; i++) {
        int j = 0;
        int Position = (Keys[i] % N + (13 - (Keys[i] % 13)) * j) % N;
        while (A[Position] != 0) {
            j = j + 1;
            Position = (Keys[i] % N + (13 - (Keys[i] % 13)) * j) % N;
        }
        A[Position] = Keys[i];          
    }
for (int i = 0; i < A.length; i++) {
        System.out.println(A[i]);
    }       
}

2019-06-17

原創文章,轉載請註明: 轉載自併發編程網 – ifeve.com本文鏈接地址: 如何使用java實現Open Addressing

FavoriteLoading添加本文到我的收藏
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章