大佬教程收集整理的这篇文章主要介绍了Ruby实现的3种快速排序算法,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
刚学Ruby,正巧算法老师鼓励用不熟悉的语言来写算法,我就用Ruby吧~~
话说Ruby可真是超厉害,好多凭直觉的方法都可以用。。。。。无限膜拜中。。。。
期间我遇到了invalid multibyte char (US-ASCII)的错误,解决办法是在开头加一个#encoding:utf-8
这个错误在stackoverflow上有人问到过,某人给出的回答是
Write # encoding: utf-8 on top of that file. That changes the default encoding of all String/regexp literals in that file utf-8.
参考链接:http://stackoverflow.com/questions/3678172/ruby-1-9-invalid-multibyte-char-us-ascii
快速排序的普通版本:
arrayInt = Array.new
index = 0
while (index < 12)
arrayInt[index] = rand(100) #produce 12 random number
index += 1
end
puts "The original array is:" + arrayInt.to_s
def QuickSort(arrayInt,first,last)
if first < last
middle = Partition(arrayInt,last)
QuickSort(arrayInt,middle - 1)
QuickSort(arrayInt,middle + 1,last)
end
end
def Partition(arrayInt,last)
x = arrayInt[last]
i = first - 1
for j in first .. (last - 1)
if arrayInt[j] <= x
i += 1
arrayInt[i],arrayInt[j] = arrayInt[j],arrayInt[i] #exchange
end
end
arrayInt[i + 1],arrayInt[last] = arrayInt[last],arrayInt[i + 1]
return i + 1
end
QuickSort(arrayInt,arrayInt.length-1)
puts "The sorted array is: " + arrayInt.to_s
快速排序的随机化版本:
arrayInt = Array.new
index = 0
while (index < 12)
arrayInt[index] = rand(100) #produce 12 random number
index += 1
end
puts "The original array is:" + arrayInt.to_s
def RandomizedQuickSort(arrayInt,last)
if first < last
middle = RandomizedPartition(arrayInt,last)
RandomizedQuickSort(arrayInt,middle - 1)
RandomizedQuickSort(arrayInt,last)
end
end
def RandomizedPartition(arrayInt,last)
i = rand(last - first + 1) + first
arrayInt[i],arrayInt[i]
return Partition(arrayInt,last)
end
def Partition(arrayInt,arrayInt[i + 1]
return i + 1
end
RandomizedQuickSort(arrayInt,arrayInt.length-1)
puts "The sorted array is: " + arrayInt.to_s
快速排序的利用了Ruby的语法糖的随机化版本:
arrayInt = Array.new
index = 0
while (index < 12)
arrayInt[index] = rand(100) #produce 12 random number
index += 1
end
puts "The original array is:" + arrayInt.to_s
def RandomizedQuickSort(a)
i = rand(a.length)
a[i],a[a.length - 1] = a[a.length - 1],a[i]
(x=a.pop) ? RandomizedQuickSort(a.SELEct{|i| i <= x}) + [x] + RandomizedQuickSort(a.SELEct{|i| i > x}) : []
end
puts "The sorted array is: " + RandomizedQuickSort(arrayint).to_s
以上是大佬教程为你收集整理的Ruby实现的3种快速排序算法全部内容,希望文章能够帮你解决Ruby实现的3种快速排序算法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。