冒泡排序

算法 / 排序

-- 时间复杂度 O(n^2)
-- 空间复杂度 O(1)
-- 相邻元素互换位置,直到一趟没有交换为止:
-- 最大的元素会冒泡到末尾
local function bubble_sort(data)
  local items = table.move(data, 1, #data, 1, {})
  for last = #items, 2, -1 do
    local swapped = false
    for j = 2, last do
      if items[j] < items[j - 1] then
        -- 不用临时变量交换
        items[j - 1], items[j] =
          items[j], items[j - 1]
        swapped = true
      end
    end
    if not swapped then
      break
    end
  end
  return items
end

local items = {4, 1, 5, 3, 2}
local sort_items = bubble_sort(items)
-- items = 4, 1, 5, 3, 2
-- sort_items = 1, 2, 3, 4, 5

print("items = " .. table.concat(items, ", "))
print("sort_items = " ..
      table.concat(sort_items, ", "))

-- *** 简易速度测试 ***
items = {}
for n = 1, 199 do
  items[n] = 200 - n
end
local count = 100

local start = os.clock()
for _ = 1, count do
  bubble_sort(items)
end
local total_ms = (os.clock() - start) * 1000

-- 耗时取决于机器
print(string.format("total_ms = %.2f", total_ms))