将元素插入排序列表 [英] Inserting an element into a sorted list
问题描述
好吧,我使用getShared preferences来存储我的高分,但在我填满它,我想通过和阵列得分按升序进行排序,但如果发现比它更低的分数在第一POS那么它不会检查其余为最小?
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);
}
我应该叫sortArray()之前和循环之后,以解决这个问题,或者有更好的方法来达到同样的效果?
should I call sortArray() before and after the loop to fix this problem or is there a better method to achieve the same results?
我还要提到的是,sortArray(分数)函数只调用Arrays.sort(评分)
其中,得分mScore数组
I should also mention that the sortArray(score) function is just calling Arrays.sort(score) where score is an array of mScore
编辑:
基于什么@Vincent Ramdhanie贴出我修改了帖子:
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;
}
}
我仍然认为,这将跌出榜单时,在的for(int i = 0; I&LT; POS;我++){
循环
推荐答案
为什么不保持排序得分的数组。所以,你的加比分到数组将假定数组降序排列所有的时间排序。要插入新的分数将只需按得分最低落阵,因为它被插入。然后,您可以使用插入算法是这样的:
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:
insertScore(int[] scores, int mscore){
//find insert point
int i = 0;
while(i < scores.length && scores[i] > mscore){
i++;
}
if(i < scores.length){
//you found a place to insert the score
for(int j = scores.length-1; j > i; j--){
scores[j] = scores[j - 1];
}
scores[i] = mscore;
}
}
在这种情况下,没有必要诉诸阵列
In this case there is no need to resort the array.
这篇关于将元素插入排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!