Ruby 快速排序无法使用稍大的数组大小
下面是我在ruby中的快速排序代码,对于20-25这样的数组大小,它工作得很好,但要么堆栈级别错误太深,要么陷入更长的时间 我猜我犯了一个很小的错误,但没能弄明白Ruby 快速排序无法使用稍大的数组大小,ruby,algorithm,sorting,data-structures,quicksort,Ruby,Algorithm,Sorting,Data Structures,Quicksort,下面是我在ruby中的快速排序代码,对于20-25这样的数组大小,它工作得很好,但要么堆栈级别错误太深,要么陷入更长的时间 我猜我犯了一个很小的错误,但没能弄明白 # This program is to do sorting using Quick sort. require 'colorize' class QuickSort attr_accessor :array def initialize(size) puts "Generating Random numbers
# This program is to do sorting using Quick sort.
require 'colorize'
class QuickSort
attr_accessor :array
def initialize(size)
puts "Generating Random numbers for your array".cyan
@array = (1..size.to_i).map do
rand(500) # Generating random numbers between 1 to 500.
end
# Boundary case
if @array.size == 1
puts "Your sorted array is"
p @array
return
end
puts "Array Before Sorting".yellow
p @array
@head = 0
@tail = @array.size-1
startSort(@array,@head,@tail) #Start the searching logic.
end
# Quicksort logic
def startSort(array,head,tail)
if head < tail
pivot = partitionArray(array,head,tail) # Calling the sorting logic
startSort(array,head,pivot-1)
startSort(array,pivot+1,@tail)
end
end
# This method is called to partition the array based on pivot.
def partitionArray(array,head,tail)
pivot_value = array[(head+tail)/2] # Choosing random pivot value.
# Run this partition step until head is equal to tail
while head <= tail
if array[head] < pivot_value
head += 1
elsif array[head] >= pivot_value
if array[tail] > pivot_value
tail -= 1
elsif array[tail] <= pivot_value
# Swapping head and tail values
temp = array[head]
array[head] = array[tail]
array[tail] = temp
# Moving each pointer forward from both the directions.
head += 1
tail -= 1
end
end
end
return head # Nothing but pivot
end
end
puts "Enter the size of Array"
@size = gets.chomp
# Checking if entry is a valid integer or not.
if @size.match(/^(\d)+$/)
@obj = QuickSort.new(@size)
puts "Array after sorting is ".green
p @obj.array
else
puts "Invalid Entry".red
end
#此程序使用快速排序进行排序。
需要“着色”
类快速排序
属性存取器:数组
def初始化(大小)
放置“为数组生成随机数”。青色
@数组=(1..size.to_i).map do
兰德(500)#生成1到500之间的随机数。
结束
#边界情况
如果@array.size==1
放置“您的排序数组为”
p@array
返回
结束
放置“排序前数组”。黄色
p@array
@水头=0
@tail=@array.size-1
startSort(@array,@head,@tail)#启动搜索逻辑。
结束
#快速排序逻辑
def startSort(阵列、头部、尾部)
如果头<尾
pivot=partitionArray(array,head,tail)#调用排序逻辑
startSort(阵列、头部、枢轴-1)
开始排序(数组,枢轴+1,@tail)
结束
结束
#调用此方法以基于pivot对阵列进行分区。
def分区阵列(阵列、头部、尾部)
pivot_值=数组[(头+尾)/2]#选择随机pivot值。
#运行此分区步骤,直到head等于tail
而头部=枢轴值
如果数组[tail]>pivot\u值
尾部-=1
elsif数组[tail]您的快速排序算法实现不正确。一行:
startSort(数组,pivot+1,@tail)
对于pivot+1
和array.size-1
,您总是调用startSort
方法,因为@tail
是一个实例变量。它只分配给@array.size-1一次,其值永远不会更改。但是,只需将此行更改为
startSort(数组、轴+1、尾)
不足以修复您的代码。通过此更改,即使对于大型阵列,它也可以快速工作,但会产生错误的答案。这一行实际上应该是:
开始排序(数组、枢轴、尾部)
通过此更改,它可以快速处理大型阵列,并正确排序阵列。您可以发布完整的代码吗?我看不出你发布的代码中定义了@tail
。嘿@User089247,我保留了整个代码。你也可以让我知道我的编码练习如何。至少最后一个要求似乎更适合我。