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.
Why not keep the array of scores sorted. So your add score to array will assume that the array is sorted in descending order all the time. The new score to be inserted will simply push the lowest score off the array as it is inserted. You can then use an insert algorithm something like this:
In this case there is no need to resort the array.