Advertisement
aripon

Hash

Apr 23rd, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.66 KB | None | 0 0
  1. class Data {
  2.  
  3. private int data;
  4.  
  5. public Data(int data) {
  6. this.data = data;
  7. }
  8.  
  9. public int getKey() {
  10. return data;
  11. }
  12. }
  13.  
  14. class HashTable {
  15.  
  16. private Data[] hashArray;
  17. private int size;
  18.  
  19. public HashTable(int size) {
  20. this.size = size;
  21. hashArray = new Data[size];
  22. }
  23.  
  24. public void displayTable() {
  25. System.out.println("Table: ");
  26. for (int j = 0; j < size; j++) {
  27. if (hashArray[j] != null) {
  28. System.out.println(" | " + j + "\t | "
  29. + hashArray[j].getKey() + " |");
  30. } else {
  31. System.out.println(" | " + j + "\t | -- |");
  32. }
  33. }
  34. System.out.println("");
  35. }
  36.  
  37. public int hashFunc(int key) {
  38. return key % size;
  39. }
  40.  
  41. public int hashFunc2(int key){
  42. return 7 - (key % 7);
  43. }
  44.  
  45. public void insert(int data) {
  46. Data item = new Data(data);
  47. int key = item.getKey();
  48. int hashVal = hashFunc(key);
  49. int hashVal2 = hashFunc2(key);
  50. //tabrakan
  51. while (hashArray[hashVal] != null) {
  52. int hashValue = hashVal+hashVal2;
  53. hashVal = hashValue % size;
  54. }
  55. hashArray[hashVal] = item;
  56. }
  57.  
  58. public Data delete(int key) {
  59. int hashVal = hashFunc(key);
  60. while (hashArray[hashVal] != null) {
  61. if (hashArray[hashVal].getKey()
  62. == key) {
  63. Data temp = hashArray[hashVal];
  64. hashArray[hashVal] = null;
  65. return temp;
  66. }
  67. ++hashVal;
  68. hashVal %= size;
  69. }
  70. return null;
  71. }
  72.  
  73. public boolean find(int key) {
  74. int hashVal = hashFunc(key);
  75. int hashVal2 = hashFunc2(key);
  76. while (hashArray[hashVal] != null) {
  77. if (hashArray[hashVal].getKey() == key ) {
  78. return true;
  79. }
  80. int hashValue = hashVal+hashVal2;
  81. hashVal = hashValue % size;
  82. }
  83.  
  84. return false;
  85. }
  86. }
  87.  
  88. public class Nim_ganjil {
  89. public static void main(String[] args) {
  90. HashTable hash = new HashTable(10);
  91. hash.insert(15);
  92. hash.insert(18);
  93. hash.insert(25);
  94. hash.insert(28);
  95. hash.insert(36);
  96. hash.insert(10);
  97.  
  98. hash.displayTable();
  99.  
  100.  
  101. int key = 28;
  102.  
  103. System.out.println("Cari nilai = "+key);
  104. if (hash.find(key)) {
  105. System.out.println("Nilai "+key+" ditemukan");
  106. } else {
  107. System.out.println("Nilai "+key+" tidak ditemukan");
  108. }
  109. }
  110.  
  111.  
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement