Lua implements basic sorting algorithms

Bubble Sort

The algorithm compares two adjacent elements through nested loops, and if the former element is greater than the latter element, their positions are exchanged. This process is repeated until no pair of adjacent elements need to be swapped.
the bigger the back
The bigger the back, the smaller the front, the bigger the back

function BubbleSort(arr)
	local count = #arr
    for i=1,count-1 do
        for j=1 , count - i do
            if arr[j] > arr[j+1] then
                arr[j],arr[j+1]=arr[j+1],arr[j]
            end
        end
    end
end

--test
local arr = {
    
    3, 9, 4, 7, 2, 0, 1, 8, 6, 5}
BubbleSort(arr)
for i, v in ipairs(arr) do
  print(v)
end

insert image description here

quick sort

The algorithm works by recursively dividing the array into smaller subarrays and calling the partition() function on each subarray. The partition() function selects the last element in the array as the pivot element, and divides the array into two parts, one part contains all elements less than or equal to the pivot element, and the other part contains all elements greater than the pivot element. Finally returns the position of the pivot element in the sorted array.

function quick_sort(arr, low, high)
  if not low then low = 1 end
  if not high then high = #arr end

  if low < high then
    local p = partition(arr, low, high)
    quick_sort(arr, low, p - 1)
    quick_sort(arr, p + 1, high)
  end
end

function partition(arr, low, high)
  local pivot = arr[high]
  local i = low - 1

  for j = low, high - 1 do
    if arr[j] <= pivot then
      i = i + 1
      arr[i], arr[j] = arr[j], arr[i]
    end
  end

  arr[i + 1], arr[high] = arr[high], arr[i + 1]
  return i + 1
end

--test
local arr = {
    
    3, 9, 4, 7, 2, 0, 1, 8, 6, 5}
quick_sort(arr)
for i, v in ipairs(arr) do
  print(v)
end

Guess you like

Origin blog.csdn.net/Brave_boy666/article/details/129898439