⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class1.cs

📁 C#2005 实例源代码
💻 CS
字号:
using System;
using System.Collections;

namespace SortedList_Search
{
	/// <summary>
	/// SortedList示例:搜索哈西表
	/// 哈西函数:key = value % 13
	/// </summary>
	class MySortedList
	{
		public SortedList slResult=new SortedList();	//所构造的哈西表

		/// <summary>
		/// 向哈西表中添加一个新的元素
		/// </summary>
		/// <param name="_intNewItem">所要添加的元素</param>
		public void AddItem(int _intNewItem)
		{
			//定义变量
			int pkey=_intNewItem % 13;
			int i=0;

			//线性散列,寻找合适散列位置
			while(this.slResult.Contains(pkey) && i<13)
			{
				pkey=(pkey+1)%13;
				i++;
			}

			//添加元素
			if(i<13)
				this.slResult.Add(pkey,_intNewItem);
			else
				Console.WriteLine("哈西表溢出。");
		}

		/// <summary>
		/// 在SortList中搜索给定的数据
		/// </summary>
		/// <param name="_intValue">待搜索的元素value值</param>
		/// <returns>搜索成功的元素idx值</returns>
		public int Search(int _intValue)
		{
			//首先根据哈西函数直接定位key值
			int pkey=_intValue % 13;
			int i=0;
			
			//考虑到冲突的情况,根据冲突消解线性策略继续寻找
			int idx=this.slResult.IndexOfKey(pkey);
			while(Convert.ToInt32(this.slResult.GetByIndex(idx))!=_intValue && i<13)
			{
				idx=(idx+1)%13;
				i++;
			}
			
			//返回查找成功后key值
			if(i<13)
				return idx;
			else
				Console.WriteLine("哈西表中不存在你想要寻找的数据!");
			return -1;
		}

		/// <summary>
		/// 应用程序的主入口点。
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			//实例化MySortedList对象
			MySortedList mysl=new MySortedList();
			int pValue=0;
			Console.WriteLine("输入10个整数值:");
			
			//利用MySortedList的AddItem循环添加数据
			for(int i=0;i<10;i++)
			{				
				pValue=Convert.ToInt32(Console.ReadLine());
				mysl.AddItem(pValue);
			}

			//利用foreach语句和DictionaryEntry结构,输出哈西表
			Console.WriteLine("SortList内容如下:");
			foreach(System.Collections.DictionaryEntry pair in mysl.slResult)
			{
				Console.WriteLine("{0}->{1}",pair.Key,pair.Value);
			}

			//利用MySortedList的Search方法进行搜索
			Console.WriteLine("输入需要搜索的数据:");
			pValue=Convert.ToInt32(Console.ReadLine());
			int idx=mysl.Search(pValue);
			if(idx!=-1)
			{
				Console.WriteLine("搜索结果为:{0}->{1}",mysl.slResult.GetKey(idx),mysl.slResult.GetByIndex(idx));
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -