题目描述

已知Hash表的表长MaxSize为11,Hash函数为HashFunc(k)=k%11,冲突处理方法为线性探测法,部分代码如下,勿改动。请补充完成成员函数HashSearch,该函数的功能是动态查找k,若查找失败,则插入k,并返回查找失败所需的比较次数,若查找成功,返回查找k所需的比较次数,若表满,则抛出异常“Overflow”
#include
using namespace std;
const int MaxSize=11; //hash表的表长,即教材中的m
class HashList
{
private:
int ht[MaxSize]; // hashtable
public:
int HashFunc(int k); //hash function
HashList(); //consturctor
void Display(); //display
int HashSearch(int k); //dynamic search k
double HashASL(); //search ASL
};
//hash function
int HashList::HashFunc(int k)
{
return k%MaxSize; //hash函数,假设为除余法,余数为MaxSize
}
//constructor:initialize an empty hashlist
HashList::HashList()
{
int i;
for(i=0;i ht[i]=-1; //-1 is empty
}
void HashList::Display()
{
int i;
for(i=0;i cout< cout<}
double HashList::HashASL()
{
double ASL=0;
int i,n=0;
for(i=0;i if(ht[i]!=-1)
{
ASL+=HashSearch(ht[i]);
cout< n++;
}
// cout< return ASL/n;
}
//在下面补充动态查找算法
int main()
{
HashList HL;
// HL.Display();
while(1)
{
int k;
cin>>k;
if(!k) break;
try{
HL.HashSearch(k);
}
catch(const char *ms)
{
cout< }
}
HL.Display();
cout<<”ASL=”< return 0;
}

输入

输入数据以0结束,依次实现动态查找。

输出

输出数据 (各行数据依次为):
hash表中的数据的输出;
各个元素的值及其查找次数;
ASL值

样例输入

47 7 29 11 16 92 22 8 3 29 0

样例输出

11 22 -1 47 92 16 3 7 29 8 -1
11 1
22 2
47 1
92 1
16 1
3 4
7 1
29 2
8 2
ASL=1.66667

提示

来源

提交

  1. import java.util.Scanner;
  2. class HashList{
  3. int MaxSize = 11;
  4. int[] ht = new int[MaxSize];
  5. int HashFunc(int k) {
  6. return k%MaxSize;
  7. }
  8. public HashList() {
  9. for(int i=0;i<MaxSize;i++)
  10. ht[i]=-1;
  11. }
  12. void Display(){
  13. for (int i=0;i<MaxSize;i++)
  14. System.out.print(ht[i]+" ");
  15. System.out.println();
  16. }
  17. int HashSearch(int k) throws Exception {
  18. int j = HashFunc(k);
  19. if (ht[j] == k)
  20. return 1;
  21. else if (ht[j] == -1)
  22. ht[j] = k;
  23. else {
  24. int i = (j + 1) % MaxSize;
  25. int cnt = 1;
  26. while (ht[i] != -1 && i != j) {
  27. cnt++;
  28. if (ht[i] == k) {
  29. return cnt;
  30. } else
  31. i = (i + 1) % MaxSize;
  32. }
  33. if(i == j) throw new Exception("Overflow");
  34. else {
  35. ht[i] = k;
  36. }
  37. }
  38. return -1;
  39. }
  40. double HashASL() throws Exception {
  41. double ASL=0;
  42. int n=0;
  43. for(int i=0;i<MaxSize;i++)
  44. if(ht[i]!=-1) {
  45. ASL+=HashSearch(ht[i]);
  46. System.out.println(ht[i] + " " + HashSearch(ht[i]));
  47. n++;
  48. }
  49. return (double)Math.round(ASL/n*100000)/100000;
  50. }
  51. }
  52. public class Main {
  53. public static void main(String[] args) throws Exception {
  54. HashList hashList = new HashList();
  55. Scanner scanner = new Scanner(System.in);
  56. while(true){
  57. int k = scanner.nextInt();
  58. if(k == 0)break;
  59. hashList.HashSearch(k);
  60. }
  61. hashList.Display();
  62. System.out.println("ASL="+hashList.HashASL());
  63. }
  64. }