Ruby实现的合并排序算法
程序员文章站
2022-04-28 22:26:03
算法课的作业,利用分治法,合并排序。
#encoding: utf-8
#author: xu jin, 4100213
#date: oct 27, 201...
算法课的作业,利用分治法,合并排序。
#encoding: utf-8 #author: xu jin, 4100213 #date: oct 27, 2012 #mergesort #to sort an array by using mergesort algorithm #example output: #the original array is:[4, 32, 84, 58, 49, 40, 75, 29, 82, 21, 70, 37, 70] #the sorted array is: [4, 21, 29, 32, 37, 40, 49, 58, 70, 70, 75, 82, 84] max = 100 arrayint = array.new for index in (0..12) arrayint[index] = rand(100) #produce 12 random number end puts "the original array is:" + arrayint.to_s def merge(arr, left, middle, right) arrl ,arrr = array.new, array.new arrl[0..(middle - left)], arrr[0..(right - middle - 1)] = arr[left..middle], arr[middle + 1.. right] arrl[arrl.size] ,arrr[arrr.size]= max, max for k in (left..right) arrl.first <= arrr.first ? (arr[k] = arrl.shift) : (arr[k] = arrr.shift) end end def merge_sort(arr, left, right) if left < right then middle = (left + right)/2 merge_sort(arr, left, middle) merge_sort(arr, middle + 1, right) merge(arr, left, middle, right) end end merge_sort(arrayint, 0, arrayint.length-1) puts "the sorted array is: " + arrayint.to_s