编辑代码

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class SortingAndVoting {

    // 基数排序部分
    // 获取数组中的最大值
    private static int getMax(int[] arr) {
        return Arrays.stream(arr).max().getAsInt(); // 返回数组中的最大值
    }

    // 对指定位数的数进行排序
    private static void countSort(int[] arr, int exp) {
        int[] output = new int[arr.length]; // 存储排序后的数组
        int[] count = new int[10]; // 初始化计数数组

        // 计算每个位数出现的次数
        for (int value : arr) {
            count[(value / exp) % 10]++;
        }

        // 更改count[i],使其包含实际在输出数组中的位置
        for (int i = 1; i < 10; i++) {
            count[i] += count[i - 1];
        }

        // 构建输出数组
        for (int i = arr.length - 1; i >= 0; i--) {
            output[count[(arr[i] / exp) % 10] - 1] = arr[i];
            count[(arr[i] / exp) % 10]--;
        }

        // 将排序好的数据复制回原数组
        System.arraycopy(output, 0, arr, 0, arr.length);
    }

    // 基数排序函数
    public static void radixSort(int[] arr) {
        int m = getMax(arr); // 获取最大数

        // 从最低位开始,对每一位应用计数排序
        for (int exp = 1; m / exp > 0; exp *= 10) {
            countSort(arr, exp);
        }
    }

    // 散列表部分
    // 在散列表中检查并插入投票者
    private static boolean checkAndInsert(Map<String, Boolean> votes, String voter) {
        if (votes.containsKey(voter)) {
            return false; // 如果找到,则表示重复投票
        } else {
            votes.put(voter, true); // 标记为已投票
            return true; // 返回成功插入
        }
    }

    // 主函数
    public static void main(String[] args) {
        // 基数排序的测试部分
        int[] arr = {94, 87, 66, 42, 5, 155, 2, 19}; // 定义待排序的数组
        System.out.println("原始数组: " + Arrays.toString(arr)); // 打印原始数组
        radixSort(arr); // 应用基数排序
        System.out.println("排序后的数组: " + Arrays.toString(arr)); // 打印排序后的数组

        // 散列表的测试部分
        Map<String, Boolean> votes = new HashMap<>(); // 定义散列表来存储投票情况
        System.out.println("\n投票过程..."); // 显示投票过程
        System.out.println("小蛋的投票是" + (checkAndInsert(votes, "小蛋") ? "未重复的" : "重复的"));
        System.out.println("小红的投票是" + (checkAndInsert(votes, "小红") ? "未重复的" : "重复的"));
        System.out.println("小蛋的第二次投票是" + (checkAndInsert(votes, "小蛋") ? "未重复的" : "重复的"));
    }
}