Advertisement
ranisalt

Pure Lua Quicksort

Jan 28th, 2014
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.87 KB | None | 0 0
  1. -- função que retorna "true" se o elemento A for logicamente menor que B
  2. local comp = function(a, b)
  3.     return a <= b
  4. end
  5.  
  6. function quicksort(arr, left, right)
  7.     function partition(arr, left, right, index)
  8.         local pivot = arr[index], _index = left
  9.         arr[index], arr[right] = arr[right], arr[index]
  10.        
  11.         for i = left, right - 1 do
  12.             if comp(arr[i], pivot) then
  13.                 arr[i], arr[_index] = arr[_index], arr[i]
  14.                 _index = _index + 1
  15.             end
  16.         end
  17.         arr[_index], arr[right] = arr[right], arr[_index]
  18.         return _index
  19.     end
  20.  
  21.     if right > left then
  22.         local new_index = partition(arr, left, right, (left + right) / 2)
  23.         quicksort(arr, left, new_index - 1)
  24.         quicksort(arr, new_index + 1, right)
  25.     end
  26. end
  27.  
  28. function quicksort(arr)
  29.     quicksort(arr, 1, #arr)
  30. end
  31.  
  32. array = { 1, 5, 2, 17, 11, 3, 1, 22, 2, 37 }
  33.  
  34. quicksort(array)
  35.  
  36. for _, v in pairs(array) do
  37.     print(v)
  38. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement