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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With