📜  门| GATE-CS-2015(Set 3)|第61章(1)

📅  最后修改于: 2023-12-03 15:42:17.651000             🧑  作者: Mango

GATE-CS-2015 (Set 3) - Chapter 61

Introduction

The GATE-CS-2015 (Set 3) exam included a question related to algorithms and data structures in Chapter 61. This chapter covers the topic of Hashing and introduces the concept of Hash Tables.

Hashing

Hashing is a technique that is used to map data of arbitrary size to a fixed size. Hashing involves performing a mathematical algorithm on the input data to produce a result that is of fixed size. The result is then used to index into an array, which is called a Hash Table.

The Hash Table contains pointers to the original data, which can be retrieved using the index generated by the hashing algorithm. This technique is used widely in computer science because of its ability to provide fast access to data.

Hash Tables

A Hash Table is an array of linked lists. Each element in the array is called a bucket, and each bucket contains a linked list of elements that have the same hash value. When searching for an element in the Hash Table, the hashing algorithm is used to determine the bucket that the element should be in. Once the correct bucket is located, the linked list is searched until the element is found.

Hash Tables can be used for a variety of applications, such as symbol tables, dictionaries, and large databases. They are particularly useful in situations where fast access to large amounts of data is required.

Code Example

Here is an example implementation of a Hash Table in Python:

class HashTable:
    def __init__(self):
        self.size = 10
        self.table = [[] for _ in range(self.size)]

    def _hash_func(self, key):
        return key % self.size

    def insert(self, key, value):
        hash_val = self._hash_func(key)
        for i, (k, v) in enumerate(self.table[hash_val]):
            if k == key:
                self.table[hash_val][i] = (key, value)
                break
        else:
            self.table[hash_val].append((key, value))

    def search(self, key):
        hash_val = self._hash_func(key)
        for k, v in self.table[hash_val]:
            if k == key:
                return v
        raise KeyError(key)

This implementation uses the modular arithmetic hashing function to hash the keys. The insert() method inserts a key-value pair into the Hash Table by first calculating the hash value of the key and then inserting the pair into the linked list at the index corresponding to the hash value. The search() method searches for a key in the Hash Table by first calculating the hash value of the key and then searching the linked list at the index corresponding to the hash value.

Conclusion

The concept of Hashing and Hash Tables is an important one in computer science. Hash Tables are widely used in various applications to provide fast access to large amounts of data. Understanding the implementation and theory behind Hash Tables is essential for any programmer.