将元素插入到排序列表中

Rus*_*ill 3 java arrays sorting logic android

好吧我正在使用getSharedPreferences来存储我的高分,但是在我填写之前我想通过和数组将分数按升序排序,但是如果它在第一个pos中找到的分数小于它,则它不会检查其余的最小的?

    //function to add score to array and sort it
    public void addscoretoarray(int mScore){
    for(int pos = 0; pos< score.length; pos++){
        if(score[pos]  > mScore){
            //do nothing
        }else {
                //Add the score into that  position
                score[pos] = mScore;
                break;
            }
    }
    sortArray(score);
}
Run Code Online (Sandbox Code Playgroud)

我应该在循环之前和之后调用sortArray()来解决这个问题,还是有更好的方法来实现相同的结果?

我还要提一下,sortArray(得分)函数只是调用Arrays.sort(得分),其中得分是mScore数组

编辑:根据@Vincent Ramdhanie发布的内容,我修改了帖子:

    public void addscoretoarray(int mScore){
    int pos = score.length; 
    //sort the array (in ascending order)
    sortArray(score);

    //go though the array( in descending order) and check for a place that suits the conditions
    while(pos>=0 && score[pos] > mScore){ 
         pos--; //do nothing as score[pos] is larger than mScore
    }
     //so once a pos is found (e.g. broke out of the while loop)
     //check that it is still in the list
    if(pos >= 0){
        //if it is then move everything down 1 position
        for(int i = 0; i < pos; i++){
            score[i] = score[i+1];
        }
        //replace the initial pos with the new score
        score[pos] = mScore;
    }
}
Run Code Online (Sandbox Code Playgroud)

我仍然相信它会在for(int i = 0; i < pos; i++){循环中从列表中删除.

Evg*_*eev 5

如果我理解你的话,那么我建议你这样做

    int[] a1 = { 1, 2, 3, 4, 6 };
    int mScore = 5;

    int[] a2 = new int[a1.length + 1];
    Arrays.sort(a1);
    int p = Arrays.binarySearch(a1, mScore);
    if (p < 0) {
        p = -p - 1;
        System.arraycopy(a1, 0, a2, 0, p);
        System.arraycopy(a1, p, a2, p + 1, a1.length - p);
        a2[p] = mScore;
    }
    System.out.println(Arrays.toString(a2));
Run Code Online (Sandbox Code Playgroud)

产量

[1, 2, 3, 4, 5, 6]

请注意,它仅插入唯一值