更改数组中索引的值,将索引从旧索引开始向右移动,同时将所有索引保留在左侧

Change value of an index in an array, shift indexes starting at old index to the right, while leaving all indexes to the left intact

我有一个数组,我有一个新值,我想将其插入到我的数组中的索引处,该索引将小于其左侧的值,并大于其右侧的值。我只关心 10 个索引,超出索引 [9] 的旧值将被销毁。

我试过这样完成:

private double[] scores = {1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1};

public void newScore(double score){

    for (int i = 0; i < scores.Length; i++){

        if (score > this.scores[i]){
            Array.Copy(this.scores, i, this.scores, i + 1, this.scores.Length - i);
            this.scores[i] = score;
            break;
        }
    }
}

newScore(0.75);

//Desired result: {1.0, 0.9, 0.8, 0.75, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2};

我的目标是将 0.75 插入到 0.8 和 0.7 之间,同时所有小于 0.75 的值向右移动并且 score[9] 处的旧值消失。

我在使用 Array.Copy(); 方法时遇到问题。是否有更好的方法来完成我正在尝试做的事情,或者我犯了一个我找不到的简单错误?

我搜索了其他解决方案,但我找到的解决方案将所有索引向右或向左移动,而不是仅将小于插入值的值移动。

this.scores.Length - i 替换为 this.scores.Length - i - 1

你的样本有误:0.10 = 0.1,分数很差。

原始分数数组为 {1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1}

你的初始数组是错误的。第一个值应该是 1.0,而不是 0.1。

我会这样解决。

public void newScore(double score)
{
    var result = new double[this.scores.Length + 1];
    for (int i = 0; i < this.scores.Length; i++)
    {
        if (score > scores[i])
        {
            Array.Copy(this.scores, 0, result, 0, i);
            Array.Copy(this.scores, i, result, i + 1, this.scores.Length - i);
            result[i] = score;
            break;
        }
    }

    scores = result;
}

如果你不需要数组,我会将代码更改为:

    private List<double> scores = new List<double> { 1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1 };

    public void newScore(double score) {
        scores.Add(score);
        scores = scores.OrderByDescending(o => o).Take(scores.Count - 1).ToList();
    }