ruby - 在 Ruby 中执行冒泡排序的最佳方法是什么?
问题描述
每次我学习一门新语言时,我都会尝试在其中构建一个冒泡排序。我这样做是因为它使用了大部分常见迭代,以便我以后可以引用它。
现在,在我在(C、Python、VB)中尝试过的所有其他语言中,这(最多)是一个 20 分钟的任务......(来自 C 的栏,我遇到了内存分配问题)。
但是在 Ruby 中......我无法让它工作。我遵循了我一直使用的完全相同的公式。无需再费周折:
#!/usr/bin/ruby
unsorted = []
swapFlag = 0
count = 1 # 1 == TRUE, 0 == FALSE
temp = 0
# Fills array with random numbers
while count != 20
count += 1
unsorted[count]=rand(100)
end
# Prints unsorted numbers, for comparison
while count != 0
print "#{count} #{unsorted[count]} \n"
count -= 1
end
print "\n"
limit = unsorted.length
# This section is the problem.
# I'm assuming it's got something to do with the logic of the loop
while swapFlag == 1
swapFlag = 0
for count in 1..limit
if unsorted[count] > unsorted[count + 1]
temp = unsorted[count + 1]
unsorted[count + 1] = unsorted[count]
unsorted[count] = temp
swapFlag = 1
end
end
end
count = 0
while count != 20
count += 1
print "#{count} - #{unsorted[count]} \n"
end
我尝试使用不同的 if 循环语法,使用 .each do 方法 ... 无济于事。
解决方案
你似乎甚至没有进入while
循环:
swapFlag = 0
...
while swapFlag == 1
此外,当您修复它时,此代码可能会起作用,但它不像 Ruby。这种学习方法可以很好地理解语法和一些基本的迭代,但是该语言提供了更多功能、可读性和强大的方法来实现这一点。