zoukankan      html  css  js  c++  java
  • 用数组实现 最简 hash线性探测

    package arr;

    import java.util.Random;

    /**

    • 模拟线性寻址式hash函数

    • 模拟将1000大小包含50个数字的数组,存入大小为100的数组内(为了方便判断,我们将0的hash直接设置为0

    • 由于数字太多,所以选择random随机生成

    • @author Christie2020
      */
      public class HashDemo {
      public static void main(String[] args) {

       //制作一个测试数组
       int[] testArr = new int[1000];
       Random random = new Random();
       int[] supportArr  = new int[50];
       for (int i = 0; i < supportArr.length; i++) {
           supportArr[i] = random.nextInt(9999);
       }
      
       //输入预设置的50个数
       System.out.println("输出预设置的50个数");
       for (int i = 0; i < supportArr.length; i++) {
           if ((i+1)%5 == 0 && i != 0){
               System.out.printf(String.format("%4d
      ",supportArr[i]));
           }else {
               System.out.printf(String.format("%4d	",supportArr[i]));
           }
       }
      
       for (int i = 0; i < 50; i++) {
           testArr[random.nextInt(1000)] = supportArr[i];
       }
      
      
       HashArray hashArray = new HashArray();
       hashArray.hashArr(testArr);
      

      }

    }
    class HashArray{

    //输入一个大小1000的数组
    

    public void hashArr(int[] arr){
    //创建容器数组
    int[] targetArr = new int[100];
    //
    int temp = 0;
    for (int i = 1; i < 1000; i++) {
    temp = arr[i]%100;
    if (arr[i] != 0){
    if (targetArr[temp] == 0){ //如果当前位置为0,则直接存储
    }else {//如果当前位置不为0,则顺序向下找
    while (targetArr[temp] != 0 ){
    if (temp <100){
    temp++;
    }else {
    temp = 0;
    }

                  }
               }
               targetArr[temp] = arr[i];
           }
       }
       //输出变化后的数组
       System.out.println("输出变化后的数组");
       for (int i = 0; i < targetArr.length; i++) {
           if ((i+1)%10 == 0 && i != 0){
               System.out.printf(String.format("%4d
    ",targetArr[i]));
           }else {
               System.out.printf(String.format("%4d	",targetArr[i]));
           }
       }
    

    }

    }

  • 相关阅读:
    js入门 关于js属性及其数据类型(详解)
    js入门关于js‘i++’‘++i’和‘i--’‘--i’计算的问题
    js入门关于函数
    js入门
    Canvas
    SVG
    H5表单属性
    移动式布局之弹性布局day1
    Mysql
    PHP抽象类和接口
  • 原文地址:https://www.cnblogs.com/lms2020/p/12374178.html
Copyright © 2011-2022 走看看