lua --- merge sort

来源:互联网 发布:内存数据库 比较 编辑:程序博客网 时间:2024/06/05 17:02
--merge sortlocal function printArray(a)for i=1, #a doprint(a[i]);endendlocal function divide(a)local b = {};local c = {};local n = math.floor( #a/2);for i=1, n dob[i] = a[i];endfor i=n+1, #a doc[i - n] = a[i];endreturn b, c;endlocal mergesort;mergesort = function (inarray)--printArray(inarray)--if #inarray >=1 then--print(#inarray)--endif #inarray <= 1 then return inarray;endlocal a,b = divide(inarray)a = mergesort(a);b = mergesort(b);--mergelocal i = 1;local j = 1;local c = {};while a[i] and b[j] doif a[i] < b[j] thenc[i + j - 1] = a[i];i = i+1;elsec[i + j - 1] = b[j];j = j+1;endendwhile a[i] doc[i+j-1] = a[i];i=i+1endwhile b[j] doc[i+j-1] = b[j];j=j+1endreturn c;endarray = {sort = mergesort,out = printArray,}--test programtestarray = {12, 2, 4, 54, 67, 32 , 11, 1, 4, 45, 666}sortres = array.sort(testarray)array.out(testarray)print("sorted:")array.out(sortres)

0 0
原创粉丝点击