Ruby实现的3种快速排序算法
刚学Ruby,正巧算法老师鼓励用不熟悉的语言来写算法,我就用Ruby吧~~ 期间我遇到了invalid multibyte char (US-ASCII)的错误,解决办法是在开头加一个#encoding:utf-8 快速排序的普通版本:
复制代码 代码如下: #encoding: utf-8 #author: xu jin,4100213 #date: Oct 20,2012 #RandomizedQuickSort #to sort an array by using QuickSort #example: #The original array is:[10,35,25,67,69,52,24,40,76,6,49] #The sorted array is: [6,10,49,76] arrayInt = Array.new def QuickSort(arrayInt,first,last) def Partition(arrayInt,last) QuickSort(arrayInt,arrayInt.length-1) 快速排序的随机化版本: 复制代码 代码如下: #encoding: utf-8 #author: xu jin,2012 #RandomizedQuickSort #to sort an array by using randomized QuickSort #example: #The original array is:[14,47,46,82,92,22,44,81,59,61] #The sorted array is: [14,61,92] arrayInt = Array.new def RandomizedQuickSort(arrayInt,last) def RandomizedPartition(arrayInt,last) def Partition(arrayInt,arrayInt[i + 1] RandomizedQuickSort(arrayInt,arrayInt.length-1)
复制代码 代码如下: #encoding: utf-8 #author: xu jin,92] arrayInt = Array.new def RandomizedQuickSort(a) puts "The sorted array is: " + RandomizedQuickSort(arrayInt).to_s (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |