如何:arrayName [x] ++;工作以及在以下背景下输出的内容是什么?

时间:2018-06-15 02:09:50

标签: java arrays

有一个名为countingSort的程序,下面列出了其代码的一部分,它通过计算a中每个数字的出现次数来处理整数数组a ,然后使用计数将a的元素分配给结果数组result以确定它们的位置。

// returns a sorted copy of a, assuming that it contains
// only integers in the range 0 .. k-1
public static int[] countingSort(int[] a, int k)
{
    int[] counts = new int[k];
    for (int x : a)
    {
        counts[x]++;
    }
    ...

我感到困惑的是行counts[x]++的操作。我已经看到双加号用作增量,但从未在此上下文中使用过。我想解释一下如何处理应用程序countingSort({3,7,1,3,8,2,1}, 10),特别是上面给出的循环结束后数组counts[]的状态。

以下是上下文的完整代码:

// returns a sorted copy of a, assuming that it contains
// only integers in the range 0 .. k-1
public static int[] countingSort(int[] a, int k)
{
    int[] counts = new int[k];
    for (int x : a)
        counts[x]++;
    int total = 0;
    for (int i = 0; i < k; i++)
    {
        int oldCount = counts[i];
        counts[i] = total;
        total += oldCount;
    }
    int[] result = new int[a.length];
    for (int x : a)
    {
        result[counts[x]] = x;
        counts[x]++;
    }
    return result;
}

同样,在第三个counts[x]++循环中再次使用相同的行for

基本上,我有2个问题;

counts[x]++的功能是什么?它是如何工作的?

鉴于要处理的应用程序是countingSort({3,7,1,3,8,2,1}, 10),第一个counts[]循环结束时for数组的状态是什么?

2 个答案:

答案 0 :(得分:3)

counts[x]++将增加数组x的索引counts处存在的数字。

使用这些信息,应该很容易预测第一个for循环后的值是什么。

答案 1 :(得分:3)

counts[x]++ 

等同于以下

int i = count[x];
i++;
count[x] = i;

第一次计数实例化时,其中的所有项都是0

  

鉴于要处理的申请是countSort({3,7,1,3,8,2,1},10)

结果将是

[0, 2, 1, 2, 0, 0, 0, 1, 1, 0] // two copies of 1 and 3, one copy of 2,7,8.
相关问题