Algorithm - How to implement score ranking using PHP, any good ideas?
世界只因有你2017-05-16 13:16:24
0
5
1206
Make a ranking of students' scores. The scores are an array. After ranking, the ranking results are output: For example, $scores = array(90,100,100); Custom function implementation returns array $rank(3,1,1);
What the questioner wants is to display the rankings in the order of the original array (can be tied). The general idea is to supplement the original array with position information, and then reversely construct the ranking array based on the sorted results. It’s a bit long to write out:
get_ranks(a[1:n])
s ← array(n)
ranks ← array(n)
for i from 1 to n ▷ s[i] has record type
s[i] ← {position: i, value: a[i], rank: 0}
descending_sort(s by value) ▷ sort by s[i].value
s[1].rank ← 1
for i from 2 to n
if s[i].value < s[i-1].value ▷ dense rank
s[i].rank ← s[i-1].rank + 1
else
s[i].rank ← s[i-1].rank
for i from 1 to n ▷ construct result
ranks[s[i].position] ← s[i].rank
return ranks[]
Note that if there are multiple nth people tied for the nth place, the next person will be the n+1th person, which is a bit different from the example given by the questioner. The complexity bottleneck of the entire algorithm is sorting, which is O(n lgn).
<?php
?>
This can meet your needs, but I have a question. The two are tied for first place. Shouldn’t the one who got 99 in the exam be the second place?
What the questioner wants is to display the rankings in the order of the original array (can be tied). The general idea is to supplement the original array with position information, and then reversely construct the ranking array based on the sorted results. It’s a bit long to write out:
Note that if there are multiple nth people tied for the nth place, the next person will be the n+1th person, which is a bit different from the example given by the questioner. The complexity bottleneck of the entire algorithm is sorting, which is O(n lgn).
Use PHP’s own array sorting function?
First sort this array by score, and then revsert this array. Then just get the key according to the score.
In addition: your scores are not written in the database, so they are taken out in order