sidrs

[TODO] DSAL_AS Ass 1 - Quad Probing

Jan 12th, 2025
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #### Quadratic Probing method for handling collisions
  2.  
  3. def insert(hasht, n):
  4.     key = int(input("Enter the value to be inserted: "))
  5.     loc = key % n
  6.     if (hasht[loc] == -1):
  7.         hasht[loc] = key
  8.     else:
  9.         i = 0
  10.         mloc = loc
  11.         while (hasht[mloc] != -1):
  12.             mloc = loc
  13.             mloc = (mloc + (i ** 2)) % n
  14.             i += 1
  15.         hasht[mloc] = key
  16.    
  17. def display(hasht):
  18.     print("\nHashtable: ", hasht)
  19.  
  20.  
  21. def search(hasht, size):
  22.     key = int(input("Enter the element to be searched: "))
  23.     start = key % size
  24.     i = start
  25.     flag = 0
  26.     found = -1
  27.     while (True):
  28.         if (hasht[i] == key):
  29.             flag = 1
  30.             found = i
  31.             break
  32.         else:
  33.             flag = 0
  34.             inc = 0
  35.         inc += 1
  36.         i = (i + (inc ** 2)) % size
  37.         if (inc > size):
  38.             flag = 0
  39.             break
  40.        
  41.     if (flag == 0):
  42.         print("\nKey not found")
  43.     if (flag == 1):
  44.         print("\nKey found at position: ", found)
  45.  
  46. def main():
  47.     size = int(input("Enter the size of the Hash Table: "))
  48.  
  49.     hasht = []
  50.     for i in range(0, size):
  51.         hasht.append(-1)
  52.  
  53.     count = 0
  54.    
  55.     while (True):
  56.         print("\n----- MENU -----")
  57.         print("1. Insert")
  58.         print("2. Display")
  59.         print("3. Search")
  60.         print("4. Exit")
  61.         ch = input("Enter your choice: ")
  62.         if ch == "1":
  63.             if (count >= size):
  64.                 print("\nCannot Insert! The Hash Table is full")
  65.             else:
  66.                 insert(hasht, size)
  67.                 display(hasht)
  68.                 count += 1
  69.         elif ch == "2":
  70.             display(hasht)
  71.         elif ch == "3":
  72.             search(hasht, size)
  73.         elif ch == "4":
  74.             return4
  75.         else:
  76.             print("Invalid Input")
  77.  
  78.  
  79. main()
Advertisement
Add Comment
Please, Sign In to add comment