Hash Function

some bug exists there, and how to assess if a hash table is full?

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
//use open addressing and quadratic probing to solve collission

typedef struct cell* ptrToCells;
typedef struct HashTable* ptrToHashTable;

struct cell{
    int info;
    int element;
};//every slot in the hash table, and slot==1

struct HashTable{
    int size;
    ptrToCells theCells; 
};//hash table

int IsPrime(int n){
//check if number n is prime
    if(n==1)
        return 0;
    if(n==2)
        return 1;
    for(int i=2; i<n; i++){
        if(n%i==0)
            return 0;
    }
    return 1;
}

int Redefine(int size){
//redefine size to be a prime
    while(IsPrime(size)==0)
        size++;
    return size;
}


int Find(int number, ptrToHashTable H){
//find the right position for number 
    int curPos = number%H->size;
    //f(i) = i%size
    int collision_time = 0;
    while(H->theCells[curPos].info!=0&&H->theCells[curPos].element!=number){

        if(collision_time>H->size)return -1;//because we can't gaurantee the load factor<0.5

        collision_time++;
        curPos = (number%H->size+collision_time*collision_time)%H->size;

    }
    return curPos;
}

int Insert(int number, ptrToHashTable H){
    int Pos = Find(number, H);
    if(Pos>=0){
        H->theCells[Pos].info = 1;
        H->theCells[Pos].element = number;  
        return Pos; 
    }
    else return -1;

}

int main(){
    ptrToHashTable H = (ptrToHashTable)malloc(sizeof(struct HashTable));
    int num, tmp, size;
    scanf("%d%d", &size, &num);
    H->size = Redefine(size);

    H->theCells = (ptrToCells)malloc(H->size*sizeof(struct cell));
    //allocate cells

    for(int i=0; i<H->size; i++)
        H->theCells[i].info = 0;
        //initiallize the cells, and mark them to be unsigned

    int tmp_Pos;

    for(int i=0; i<num-1; i++){
        scanf("%d", &tmp);
        tmp_Pos = Insert(tmp,  H);
        if(tmp_Pos!=-1)
            printf("%d ",tmp_Pos);
        else
            printf("- ");
    }

    if(num!=0){
        scanf("%d", &tmp);
        tmp_Pos = Insert(tmp,  H);
        if(tmp_Pos!=-1)
            printf("%d",tmp_Pos);
        else
            printf("-");    
    }
    /*for(int i=0; i<H->size; i++)
        printf("%d %d\n", H->theCells[i].element, H->theCells[i].info);
    */


}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值