散列表(哈希表)

2022-08-28  本文已影响0人  lxr_

散列表

散列函数

处理散列冲突

代码示例

Hash.h

#pragma once

#define HASHSIZE 12         //定义散列表长为数组的长度
#define NULLKEY -32768

struct HashTable
{
    int* elem;              //数据元素存储基址,动态分配数组
    int count;              //当前数据元素个数
};

//初始化散列表
bool InitHashTable(HashTable& H);

//散列函数
int Hash(int key);

//插入关键字到散列表
void InsertHash(HashTable& H, int key);

//散列表查找关键字
bool SearchHash(HashTable H, int key, int* addr);

Hash.cpp

#include "Hash.h"

//初始化散列表
bool InitHashTable(HashTable& H)
{
    H.elem = new int[HASHSIZE];
    H.count = HASHSIZE;
    for (int i = 0; i < H.count; i++)
    {
        H.elem[i] = NULLKEY;
    }
    return true;
}

//散列函数
int Hash(int key)
{
    return key % HASHSIZE;                  //除留余数法
}

//插入关键字到散列表
void InsertHash(HashTable& H, int key)
{
    int addr = Hash(key);           //求散列地址

    while (H.elem[addr] != NULLKEY) //开放定址法的线性探测
    {
        addr = (addr + 1) % H.count;
    }

    H.elem[addr] = key;
}

//散列表查找关键字
bool SearchHash(HashTable H, int key, int* addr)
{
    *addr = Hash(key);
    while (H.elem[*addr] != key)
    {
        *addr = (*addr + 1) % H.count;

        if (H.elem[*addr] == NULLKEY || *addr == Hash(key))
        {
            //如果循环到原点,说明关键字不存在
            return false;

        }
    }

    return true;
}

main.cpp

#include "Hash.h"

#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    int arr[HASHSIZE] = { 12,67,56,16,25,37,22,29,15,47,48,34 };

    HashTable H;
    if (InitHashTable(H))
    {
        cout << "初始化成功" << endl;
    }
    else
    {
        cout << "初始化失败" << endl;
    }

    for (int i = 0; i < H.count; i++)
    {
        InsertHash(H, arr[i]);
    }

    int key = 34;
    int addr = 0;
    if (SearchHash(H, key, &addr))
    {
        cout << "找到了,addr=" << addr << endl;
    }
    else
    {
        cout << "未找到" << endl;
    }

    for (int i = 0; i < H.count; i++)
    {
        SearchHash(H, arr[i], &addr);
        cout << arr[i] << ":" << addr << endl;
    }
    cout << endl;

    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读