sort.lua 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. print"testing sort"
  2. function check (a, f)
  3. f = f or function (x,y) return x<y end;
  4. for n=table.getn(a),2,-1 do
  5. assert(not f(a[n], a[n-1]))
  6. end
  7. end
  8. a = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  9. "Oct", "Nov", "Dec"}
  10. table.sort(a)
  11. check(a)
  12. limit = 30000
  13. if rawget(_G, "_soft") then limit = 5000 end
  14. a = {}
  15. for i=1,limit do
  16. a[i] = math.random()
  17. end
  18. local x = os.clock()
  19. table.sort(a)
  20. print(string.format("Sorting %d elements in %.2f sec.", limit, os.clock()-x))
  21. check(a)
  22. x = os.clock()
  23. table.sort(a)
  24. print(string.format("Re-sorting %d elements in %.2f sec.", limit, os.clock()-x))
  25. check(a)
  26. a = {}
  27. for i=1,limit do
  28. a[i] = math.random()
  29. end
  30. x = os.clock(); i=0
  31. table.sort(a, function(x,y) i=i+1; return y<x end)
  32. print(string.format("Invert-sorting other %d elements in %.2f sec., with %i comparisons",
  33. limit, os.clock()-x, i))
  34. check(a, function(x,y) return y<x end)
  35. table.sort{} -- empty array
  36. for i=1,limit do a[i] = false end
  37. x = os.clock();
  38. table.sort(a, function(x,y) return nil end)
  39. print(string.format("Sorting %d equal elements in %.2f sec.", limit, os.clock()-x))
  40. check(a, function(x,y) return nil end)
  41. for i,v in pairs(a) do assert(not v or i=='n' and v==limit) end
  42. a = {"álo", "\0first :-)", "alo", "then this one", "45", "and a new"}
  43. table.sort(a)
  44. check(a)
  45. table.sort(a, function (x, y)
  46. -- loadstring(string.format("a[%q] = ''", x))()
  47. -- collectgarbage()
  48. return x<y
  49. end)
  50. tt = {__lt = function (a,b) return a.val < b.val end}
  51. a = {}
  52. for i=1,10 do a[i] = {val=math.random(100)}; setmetatable(a[i], tt); end
  53. table.sort(a)
  54. check(a, tt.__lt)
  55. check(a)
  56. print"OK"