Advertisement
nein_yards

HashTable Object Oriented

Oct 14th, 2020 (edited)
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. Class HashTable
  2. Public table() As Integer?
  3. Private size As Integer
  4. Sub New(maxIndex As Integer)
  5. size = maxIndex + 1
  6. ReDim table(maxIndex)
  7. End Sub
  8. Sub print()
  9. For i = 0 To size - 1
  10. Console.WriteLine(i & " : " & table(i))
  11. Next
  12. End Sub
  13. Function insert(key As Integer) As Integer
  14. 'returns 1 for success, 0 for failure
  15. Dim address As Integer = hash(key)
  16. Dim initialAddress As Integer = address
  17. While Not table(address) Is Nothing
  18. address += 1
  19. If address >= size Then
  20. address = 0
  21. End If
  22. If address = initialAddress Then
  23. Console.WriteLine("ERROR - Hash table is full!")
  24. Return 0
  25. End If
  26. End While
  27. table(address) = key
  28. Return 1
  29. End Function
  30. Function searchIndex(key As Integer) As Integer
  31. 'returns -1 if not found
  32. Dim address As Integer = hash(key)
  33. Dim initialAddress As Integer = address
  34. While table(address) Is Nothing Or table(address) <> key
  35. address += 1
  36. If address >= size Then
  37. address = 0
  38. End If
  39. If address = initialAddress Then
  40. Return -1
  41. End If
  42. End While
  43. Return address
  44. Return 1
  45. End Function
  46. Function hash(key) As Integer
  47. Return key Mod size
  48. End Function
  49. End Class
  50. Sub Main()
  51. 'demo
  52. Dim myHashTable As New HashTable(9)
  53. myHashTable.insert(8)
  54. myHashTable.insert(14)
  55. myHashTable.insert(65)
  56. myHashTable.insert(5)
  57. myHashTable.insert(53)
  58. myHashTable.insert(23)
  59. myHashTable.insert(9)
  60. myHashTable.insert(42)
  61. myHashTable.insert(91)
  62. myHashTable.insert(43)
  63.  
  64. myHashTable.print()
  65.  
  66. Console.WriteLine()
  67. Console.WriteLine(myHashTable.searchIndex(53))
  68.  
  69. Console.ReadLine()
  70. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement