Advertisement
Jameloncio

HashDUpla

Oct 22nd, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.03 KB | None | 0 0
  1. package tabelahash;
  2.  
  3. public class TabelaHashDuplo<T extends Itemble > extends TabelaHash{
  4.  
  5. TabelaHashDuplo(int tam){
  6. super(tam);
  7. }
  8.  
  9. public void inserir(Itemble elem) {
  10.  
  11. int indice = hash(elem.getKey());
  12.  
  13. if(tabela[indice] == null)
  14.  
  15. tabela[indice] = elem;
  16.  
  17. else {
  18.  
  19. int tentativa = 1;
  20. int indice2 = indice + tentativa * hash2(elem.getKey());
  21. indice2 = indice2 % tabela.length;
  22. if(indice2<0){
  23. indice *= (-1);
  24. }
  25.  
  26. while( tabela[indice2] != null ) {
  27. tentativa++;
  28. indice2 = indice + tentativa * hash2(elem.getKey());
  29. indice2 = indice2 % tabela.length;
  30. if(indice2<0){
  31. indice *= (-1);
  32. }
  33.  
  34. //voltando
  35. if (indice2 >= tabela.length) {
  36. indice2 = 0;
  37. }
  38. }
  39. tabela[indice2] = elem;
  40. }
  41.  
  42. }
  43.  
  44. public Itemble buscar(String key){
  45. int indice = hash(key);
  46.  
  47. if(tabela[indice].getKey().equalsIgnoreCase(key)){
  48. System.out.println("Não colidiu");
  49. return tabela[indice];
  50. } else {
  51. int tentativa = 1;
  52. int indice2 = indice + tentativa * hash2(key);
  53. indice2 = indice2 % tabela.length;
  54. while(tabela[indice2]==null){
  55. tentativa++;
  56. indice2 = indice + tentativa * hash2(key);
  57. indice2 = indice2 % tabela.length;
  58. if(indice2<0){
  59. indice2 *=(-1);
  60. }
  61. }
  62.  
  63. while((!tabela[indice2].getKey().equalsIgnoreCase(key))
  64. && (indice2 < tabela.length) ) {
  65. tentativa++;
  66. if(tentativa>=tabela.length){
  67. return null;
  68. }
  69. indice2 = indice + tentativa * hash2(key);
  70. indice2 = indice2 % tabela.length;
  71. if(indice2<0){
  72. indice2 *=(-1);
  73. }
  74. while(tabela[indice2]==null){
  75. tentativa++;
  76. indice2 = indice + tentativa * hash2(key);
  77. indice2 = indice2 % tabela.length;
  78. if(indice2<0){
  79. indice2 *=(-1);
  80. }
  81. }
  82. //voltando
  83. if (indice2 >= tabela.length) {
  84. indice2 = 0;
  85. }
  86. }
  87. if(indice == tabela.length)
  88. return null;
  89.  
  90. return tabela[indice2];
  91. }
  92. }
  93.  
  94. public int hash2(String key) {
  95. int indice = 0;
  96.  
  97. for(int i = key.length()-1; i >= 0; i--) {
  98. int c = (int) key.charAt(i);
  99. indice += c * Math.pow(26, key.length() - i);
  100. }
  101.  
  102. return indice % tabela.length;
  103. }
  104.  
  105.  
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement