diff --git a/lua/quicksort.lua b/lua/quicksort.lua index ec16260..2d9bc82 100644 --- a/lua/quicksort.lua +++ b/lua/quicksort.lua @@ -1,34 +1,25 @@ -function partition(array, left, right, pivotIndex) - local pivotValue = array[pivotIndex] - array[pivotIndex], array[right] = array[right], array[pivotIndex] - - local storeIndex = left - - for i = left, right-1 do - if array[i] <= pivotValue then - array[i], array[storeIndex] = array[storeIndex], array[i] - storeIndex = storeIndex + 1 +local function quicksort(t, left, right) + if right < left then return end + local pivot = left + for i = left + 1, right do + if t[i] <= t[pivot] then + if i == pivot + 1 then + t[pivot],t[pivot+1] = t[pivot+1],t[pivot] + else + t[pivot],t[pivot+1],t[i] = t[i],t[pivot],t[pivot+1] + end + pivot = pivot + 1 end - array[storeIndex], array[right] = array[right], array[storeIndex] - end - - return storeIndex -end - -function quicksort(array, left, right) - if right > left then - local pivotNewIndex = partition(array, left, right, left) - quicksort(array, left, pivotNewIndex - 1) - quicksort(array, pivotNewIndex + 1, right) end + quicksort(t, left, pivot - 1) + quicksort(t, pivot + 1, right) end - -array = { 1, 5, 2, 17, 11, 3, 1, 22, 2, 37 } +local array = { 1, 5, 2, 17, 11, 3, 1, 22, 2, 37 } quicksort(array, 1, #array) for _, v in pairs(array) do print(v) -end \ No newline at end of file +end