2
0

sort.lua 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. -- two implementations of a sort function
  2. -- this is an example only. Lua has now a built-in function "sort"
  3. -- extracted from Programming Pearls, page 110
  4. function qsort(x,l,u,f)
  5. if l<u then
  6. local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
  7. x[l],x[m]=x[m],x[l] -- swap pivot to first position
  8. local t=x[l] -- pivot value
  9. m=l
  10. local i=l+1
  11. while i<=u do
  12. -- invariant: x[l+1..m] < t <= x[m+1..i-1]
  13. if f(x[i],t) then
  14. m=m+1
  15. x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
  16. end
  17. i=i+1
  18. end
  19. x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
  20. -- x[l+1..m-1] < x[m] <= x[m+1..u]
  21. qsort(x,l,m-1,f)
  22. qsort(x,m+1,u,f)
  23. end
  24. end
  25. function selectionsort(x,n,f)
  26. local i=1
  27. while i<=n do
  28. local m,j=i,i+1
  29. while j<=n do
  30. if f(x[j],x[m]) then m=j end
  31. j=j+1
  32. end
  33. x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
  34. i=i+1
  35. end
  36. end
  37. function show(m,x)
  38. io.write(m,"\n\t")
  39. local i=1
  40. while x[i] do
  41. io.write(x[i])
  42. i=i+1
  43. if x[i] then io.write(",") end
  44. end
  45. io.write("\n")
  46. end
  47. function testsorts(x)
  48. local n=1
  49. while x[n] do n=n+1 end; n=n-1 -- count elements
  50. show("original",x)
  51. qsort(x,1,n,function (x,y) return x<y end)
  52. show("after quicksort",x)
  53. selectionsort(x,n,function (x,y) return x>y end)
  54. show("after reverse selection sort",x)
  55. qsort(x,1,n,function (x,y) return x<y end)
  56. show("after quicksort again",x)
  57. end
  58. -- array to be sorted
  59. x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
  60. testsorts(x)