我需要帮助以这种特定方式基于频率对java中的数组进行排序

问题描述 投票:0回答:1

需要帮助获取一个数组,计算频率,放入另一个数组,其数组索引以数字的形式起作用,而单个值则以Java的频率出现]

您可以通过使用n的数组计数对1到n范围内的m个整数的大型数组进行排序条目,用于计算数组中每个整数的出现次数。例如,考虑以下14个整数的数组A,范围为1到9(请注意,在这种情况下,m =14 and n = 9):

9 2 4 8 9 4 3 2 8 1 2 7 2 5

形成9个元素的数组计数,以使count [i-1]包含i的次数出现在要排序的数组中。因此,计数为

1 4 1 2 1 0 1 2 2

特别是

  • [count[0] = 1,因为1在A中出现一次。
  • count [1] = 4,因为2在A中发生4次。
  • count [2] = 1,因为3在A中出现一次。
  • count [3] = 2,因为4在A中出现2次。

使用count数组对原始数组A进行排序。在函数中实现此排序算法

public static void countingSort(int[] a, int n )

并根据m(数组a的长度)和n分析其最坏情况下的运行时间。调用countingSort()后,必须为排序数组(请勿将排序结果存储在临时数组)。

编辑:这是我尝试过的

 public static void countingSort1(int[] a, int n) {
    int [] temp = new int[n];
    int [] temp2 = new int[n];
    int visited = -1;
    for (int index = 0; index < n; index++) {
        int count = 1;
        for (int j = index +1; j < n; j++) {
            if(a[index] == a[j]) {
                count++;
                temp[j] = visited;
            }

        }
        if (temp[index]!= visited) {
            temp[index] = count;
        }
    }
    for(int i = 1; i < temp.length; i++) {
        if (temp[i] != visited) {
            System.out.println("  " +a[i] + "  |   " +temp[i]);
        }
    }

仅计算频率,但我认为我做错了

java frequency
1个回答
0
投票
如下所示应该可以完成工作:

    由于您已经知道最高值,在您的示例9中,创建一个具有9个元素的空间的频率数组。
  • 迭代输入数组,发现每个值都增加频率arra中的值的索引处的值加1
  • 为索引创建一个计数器,并将其初始化为0
  • 在嵌套循环中遍历您的频率阵列,然后替换输入数组中的值以及频率数组的索引。
  • 我将复杂性的分析留给您

    public static void countingSort(int[] a, int n ){ //counting int[] freq = new int[n]; for(int i = 0; i<a.length; i++){ freq[a[i]-1]++; } //sorting int index = 0; for(int i = 0; i< freq.length; i++){ for(int j = 0;j < freq[i];j++){ a[index++]= i+1; } } System.out.println(Arrays.toString(a)); }

  • © www.soinside.com 2019 - 2024. All rights reserved.