1. 程式人生 > >查詢(2)——雜湊查詢

查詢(2)——雜湊查詢

#include <stdio.h>
#define MAXSIZE 11
#define key 11

void insert(int hashArray[],int x){
    int i = 0;
    int t = x % key;
    while(i < MAXSIZE){
        if(hashArray[t] <= -1){
            hashArray[t] = x;
            break;
        }else{
            t = (t+1) % key;
        }
        i++;
    }
    if
(i == MAXSIZE){ printf("雜湊表已滿!\n"); } } void search(int hashArray[],int x){ int i = 0; int t = x % key; while(hashArray[t] != -1 && i<MAXSIZE){ if(hashArray[t] == x){ printf("要查詢數字的下標是:%d",t); break; }else{ t = (t+1
) % key; } i++; } if(i == MAXSIZE || hashArray[t] == -1){ printf("沒有找到!\n"); } printf("\n"); } void del(int hashArray[],int x){ int i = 0; int t = x % key; while(hashArray[t] != -1 && i < MAXSIZE){ if(hashArray[t] == x){ hashArray[t] = -2
; printf("已刪除!\n"); break; }else{ t = (t+1)%key; } i++; } if(i == MAXSIZE || hashArray[t] == -1){ printf("刪除失敗!\n"); } } void print(int hashArray[]){ for(int i=0;i<MAXSIZE;i++){ printf("%d ",hashArray[i]); } } int main(){ int hashArray[MAXSIZE]; int x,k=0; int target; int delTarget; for(int i=0;i<MAXSIZE;i++){ hashArray[i] = -1; } printf("請輸入資料!(-1停止)\n"); scanf("%d",&x); while(x != -1 && k < MAXSIZE){ insert(hashArray,x); k++; scanf("%d",&x); } printf("此時雜湊表中的內容:\n"); print(hashArray); printf("\n"); printf("請輸入要查詢的數字。\n"); scanf("%d",&target); search(hashArray,target); printf("請輸入要刪除的數字。\n"); scanf("%d",&delTarget); del(hashArray,delTarget); printf("此時雜湊表中的內容:\n"); print(hashArray); return 0; }