I make no guarantees, but I think this should work. I put it on my bot for testing purposes and didn't notice any problems.
Only thing that I can think of that might cause inaccurate results is if two (or more) people have the same amount of uptime

Code:
 on *:text:!whois:#:{
  var %a = 1
  while %a <= $nick(#,0) {
    .enable #scan
    whois $nick(#,%a)
    inc %a
  }
  set %uptime $sort(%uptime,32,n)
  var %a = 1
  while %a <= $numtok(%uptime) {
    set %nick $addtok(%nick,$hfind(uptime,$gettok(%uptime,%a,32),1),32)
    if %a < 5 .write -s $+ $nick uptime.txt $nick $gettok(%uptime,%a,32)
    inc %a
  }
}

#scan off
raw 317:*:{
  hadd -m uptime $nick(#,%a) $calc($ctime - $4)
  set %uptime = $addtok(%uptime,$calc($ctime - $4),32)
}