/MergeSort.lua

http://github.com/akosma/CodeaSort · Lua · 43 lines · 38 code · 5 blank · 0 comment · 7 complexity · 71770508f1cc8af4fc2a75e8cb1bd3a3 MD5 · raw file

  1. function mergeSort(array, p, r)
  2. p = p or 1
  3. r = r or #array
  4. if p < r then
  5. local q = math.floor((p + r) / 2)
  6. mergeSort(array, p, q)
  7. mergeSort(array, q + 1, r)
  8. merge(array, p, q, r)
  9. end
  10. return array
  11. end
  12. function merge(array, p, q, r)
  13. local n1 = q - p + 1
  14. local n2 = r - q
  15. local i
  16. local j
  17. local left = {}
  18. for i = 1, n1 do
  19. left[i] = array[p + i - 1]
  20. end
  21. left[n1 + 1] = math.huge
  22. local right = {}
  23. for j = 1, n2 do
  24. right[j] = array[q + j]
  25. end
  26. right[n2 + 1] = math.huge
  27. i = 1
  28. j = 1
  29. for k = p, r do
  30. if left[i] <= right[j] then
  31. array[k] = left[i]
  32. i = i + 1
  33. else
  34. array[k] = right[j]
  35. j = j + 1
  36. end
  37. end
  38. end