哈希查找——算法系列

哈希查找:

哈希查找是ο(1)的查找方法

其中有两点要注意“哈希函数”和“解决冲突”

哈希函数有两个标准1、key尽可能的分散,防止发生冲突。2、函数要简单,尽量不做复杂的运算。下面的代码用到的哈希函数为:除法取余,解决冲突的方法为:开放地址法。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//哈希查找程序
namespace Test
{
    class Program
    {
        static int hashLength = 13;
        static List<int> list = new List<int>() { 13, 29, 27, 28, 26, 30, 38 };
        static int[] hash = new int[hashLength];
        static void Main(string[] args)
        {
            for (int i = 0; i < list.Count; i++)
                InsertHash(hash, hashLength, list[i]);
            Console.WriteLine("Hash数据: " + string.Join(",", hash));
            while (true)
            {
                Console.WriteLine("\n请输入要查找的数字:");
                int result = int.Parse(Console.ReadLine());
                var index = SearchHash(hash, hashLength, result);
                if (index != -1)
                    Console.WriteLine("数字" + result + "在索引的位置为" + index);
                else
                    Console.WriteLine("没有找到" + result + "\n");
            }
        }

        static void InsertHash(int[] hash, int hashLength, int data)
        {
            int hashAddress = data % hashLength;

            while (hash[hashAddress] != 0)
            {
                hashAddress = (++hashAddress) % hashLength;
            }

            hash[hashAddress] = data;
        }

        static int SearchHash(int[] hash, int hashLength, int key)
        {
            int hashAddress = key % hashLength;
            while (hash[hashAddress] != 0 && hash[hashAddress] != key)
            {
                hashAddress = (++hashAddress) % hashLength;
            }
            if (hash[hashAddress] == 0)
                return -1;
            return hashAddress;
        }
    }
}

总结:哈希查找有很好的性质,也很容易理解。不过这其中还有很多其他哈希函数和解决冲突的方法,有待补充。

原文地址:https://www.cnblogs.com/7ants/p/2962332.html