一维数组, 第n大的数是多少?

来源:互联网 发布:阿里云 aws 编辑:程序博客网 时间:2024/04/28 10:14

<%
' 问题来源: 某班学生成绩放在一维数组中. 问第3名的学生成绩是多少.
'输入字符串:16,12,10,13,10
'输出结果:5,3,1,4,2
' 调用方法: FindSortID(s,3) =2
' 第3名在位置2上.' 我想要的是: 第几名在哪个位置.
' 这样可以狠方便地用 S(2) 知道第3名的成绩.
if 1=1 then
 s=array(16,12,10,13,10)  '测试数组
 for i=0 to ubound(s)
  a=FindSortID(s,i)
  response.Write " <"&a&"> "
 Next
 response.Write " <br>"
 response.Write " <"&FindSortID(s,1)&"> "
 response.Write " <"&FindSortID(s,2)&"> "
 response.Write " <"&FindSortID(s,3)&"> "
 response.Write " <"&FindSortID(s,4)&"> "
 response.Write " <"&FindSortID(s,5)&"> "
end if

Function FindSortID(s(),n)
' s=array(16,12,10,13,10)  '测试数组
 redim ac(ubound(s)) '定义一个数组, 放名次表
 for i=0 to ubound(s)
  k=1  ' 先假设排在 第一个
  for j=0 to ubound(s)
'   if j <>i then
'    if cdbl(s(i))>cdbl(s(j)) or (cdbl(s(i))=cdbl(s(j)) and i>j) then k=k+1
    ' 不够别人高分, 名次就向后排 (高分的排在前面)
    if s(i)<s(j) or (s(i)=s(j) and i<j) then k=k+1
'   end if
   ac(i)=k
  next
' 如果排名是要找的第n名,就输出它.
' 这样我可以用 S(n) 调用. 知道第n名的成绩
  if k=n then FindSortID=i+1
 next
'数组ac{1,3,5,2,4} 是一个数在数组里面第几大组成的数组
End Function
'测试结果 FindSortID(s,1)到FindSortID(s,5)等于: <1> <4> <2> <5> <3> 通过.
%>

 

 

 

 

========================

Function FindSortID(s(),n)
' s=array(16,12,10,13,10)  '测试数组
 redim ac(ubound(s)) '定义一个数组ac(), 放名次表 ac(2)值为第2名在原数组中的位置
 for i=0 to ubound(s) ' 从第0号开始计算位置
  k=1  ' 先假设排在 第一个
  for j=0 to ubound(s) ' 计算第i号排第几
    ' 不够别人高分, 名次就向后排 (高分的排在前面)
    if s(i)<s(j) or (s(i)=s(j) and i<j) then k=k+1
   ac(i)=k  '结果写到数组ac()中
  next
' 如果排名是要找的第n名,就输出它.
' 这样我可以用 S(n) 调用. 知道第n名的成绩
  if k=n then FindSortID=i+1
 next
'数组ac{1,3,5,2,4} 是一个数在数组里面第几大组成的数组
End Function
'测试结果 FindSortID(s,1)到FindSortID(s,5)等于: <1> <4> <2> <5> <3> 通过.

=======================