Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an element into a sorted list

Ok I'm using getSharedPreferences to store my high score but before I fill it up I wanted to sort the scores into ascending order via and array, but if it finds a Score less than it in the first pos then it wont check the rest for the smallest?

    //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);
}

should I call sortArray() before and after the loop to fix this problem or is there a better method to achieve the same results?

I should also mention that the sortArray(score) function is just calling Arrays.sort(score) where score is an array of mScore

EDIT: based on what @Vincent Ramdhanie posted I have revised the post:

    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;
    }
}

I still believe that it will drop off the list when in the for(int i = 0; i < pos; i++){ loop.

like image 946
Russell Cargill Avatar asked Dec 27 '22 13:12

Russell Cargill


1 Answers

If I understood your correctly then I suggest this

    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));

output

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

Note that it inserts only unique values

like image 105
Evgeniy Dorofeev Avatar answered Feb 06 '23 07:02

Evgeniy Dorofeev