快速排序实现

来源:互联网 发布:mp3网络歌曲地址 编辑:程序博客网 时间:2024/06/05 14:11

参考 :http://blog.csdn.net/hguisu/article/details/7776068

--[[1)选择一个基准元素,通常选择第一个元素或者最后一个元素,2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。3)此时基准元素在其排好序后的正确位置4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。--]]function swap(i1,i2,arr)    local tmp = arr[i2]    arr[i2] = arr[i1]    arr[i1] = tmpend function partition(arr,low,high)    local privotKey    privotKey = arr[low]    while(low < high)do        --从表的两端交替地向中间扫描,        --从high 所指位置向前搜索 --将比基准元素小的交换到低端                                             while(low < high  and  arr[high] >= privotKey) do              high = high - 1        end         swap(low,high,arr)        --从low 所指位置向后搜索                  while(low < high and  arr[low] <=  privotKey ) do             low = low + 1        end         swap(low, high,arr)    end     return lowend  function quickSort(arr,low,high)    if low < high then         local privotLoc = partition(arr,low,high);  --将表一分为二          quickSort(arr,low,privotLoc -1);          --递归对低子表递归排序          quickSort(arr,privotLoc + 1, high);       --递归对高子表递归排序      end endarr = {3,3,3,3,3,9,8,7,6,5,4}quickSort(arr,1,#arr)print(table.concat(arr,","))
原创粉丝点击