lua中快速排序的理解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010996533/article/details/79120936
快速排序的时间复杂度是:O(n * log(n))
快速排序的主要思想是分治思想

快速排序是找出一个元素作为基准,然后对数组进行分区操作,是基准左边的元素的值不大于基准值,基准右边的元素值,都不少于基准值,如此作为基准的元素调整到排序后的正确位置.

--[[--
  -   partition: 获得快排中介值位置
  -   @param: list, low, high - 参数描述
  -   @return: pivotKeyIndex - 中介值索引
  ]]
 function partition(list, low, high)
      local low = low
      local high = high
      local pivotKey = list[low] -- 定义一个中介值
    
     -- 下面将中介值移动到列表的中间
     -- 当左索引与右索引相邻时停止循环
     while low < high do
         -- 假如当前右值大于等于中介值则右索引左移
         -- 否则交换中介值和右值位置
         while low < high and list[high] >= pivotKey do
             high = high - 1
         end
         swap(list, low, high) 
         -- 假如当前左值小于等于中介值则左索引右移
         -- 否则交换中介值和左值位置
         while low < high and list[low] <= pivotKey do
            low = low + 1
         end
         swap(list, low, high)
	    end
     return low
 end
 
--[[--
 -   orderByQuick: 快速排序
 -   @param: list, low, high - 参数描述
 -    @return: list - table
]] 
function orderByQuick(list, low, high)
     if low < high then
         -- 返回列表中中介值所在的位置,该位置左边的值都小于等于中介值,右边的值都大于等于中介值
         local pivotKeyIndex = partition(list, low, high)
         -- 分别将中介值左右两边的列表递归快排
         orderByQuick(list, low, pivotKeyIndex - 1)
         orderByQuick(list, pivotKeyIndex + 1, high)
     end
end

function swap(list,low,high)
	local temp = 0
	temp = list[low]
	list[low] = list[high]
	list[high] = temp
end

local printT = function(t)
    print("printT ---------------")
    table.walk(t, function(v, k)
       	print(k, v)
    end)
    print("---------------")
end

function table.walk( t, fn )
    for k, v in pairs( t ) do
        fn( v, k )
    end
end

local test_list = {1,2,-2,3,-3444,-3344,3334,334,344,345,667,77} 

local num = #test_list
orderByQuick(test_list, 1, num) --  总结
print("after order--------")
printT(test_list)
 


运行结果

after order--------
printT ---------------
1 -3444
2 -3344
3 -2
4 1
5 2
6 3
7 77
8 334
9 344
10 345
11 667
12 3334
---------------
[Finished in 0.1s]

猜你喜欢

转载自blog.csdn.net/u010996533/article/details/79120936