Home > Blockchain >  I have implemented Linear Probing in the attached code. How can we modify it such that even negative
I have implemented Linear Probing in the attached code. How can we modify it such that even negative

Time:03-06

I'm trying to implement linear probing. I want to know how negative values are handled in this technique. In the below code, I have written a function for positive values. Also, what if -1 was an element in the array? How are we going to handle it?

int[] linearProbing(int hash_size, int arr[], int sizeOfArray)
    {
        //Your code here
        int []table = new int[hash_size];
        
        for(int i=0;i<hash_size;i  ){
            table[i] = -1;
        }
        
        int key = 0;
        for(int i=0;i<sizeOfArray;i  ){
            key = arr[i] % hash_size;
            if(table[key] == arr[i]){
                continue;
            }
            
            if(table[key] == -1){
                table[key] = arr[i];
            }
            else{
                int k = 1;
                int j = (key k) % hash_size;
                while(table[j] != -1){
                    if(j == key){
                        return table;
                    }
                    if(table[j] == arr[i]){
                        break;
                    }
                    else{
                        k  ;
                        j = (key k) % hash_size;
                    }
                }
                table[j] = arr[i];
            }
        }
        return table;
    }

CodePudding user response:

The first problem is that you use -1 to mark free slots in your table. In order to resolve this, you need some other structure to store free slots. One idea would be a boolean[] with the same length as your table.

Now, instead of checking if a slot is free with table[key] == -1 you check it with your new boolean[] (false means free slot). If you store a new value you have to set the array value to true (meaning that there is a value stored).

Another point you have to consider is the generation of the key (key = arr[i] % hash_size), which will be negative if the value to store is negative. The problem is that your table cannot handle negative keys. A simple solution to this would be to use the absolute value of the key. For example: key = Math.abs(arr[i] % hash_size)

If you implement these things your function will also be able to handle negative values.

  • Related