【问题标题】:Keeping count of swaps in a bubble sort algorithm that uses recursion?在使用递归的冒泡排序算法中保持交换计数?
【发布时间】:2017-03-26 06:41:13
【问题描述】:
def bubble_sort(a)
  something_changed = false
  swap = 0 
  a[0...-1].each_with_index do |num, i|
    if a[i] > a[i + 1]
      a[i], a[i + 1] = a[i + 1], a[i]
      something_changed = true
      swap += 1
    end
  end
  bubble_sort(a)  if something_changed
  p swap
end

arr = [50, 60, 70, 20, 30, 10]
bubble_sort(arr)
# 0
# 1
# 1
# 3
# 3
# 3

所以我已经做了很长一段时间,并尝试了各种方式。我已经设法理解了数组是如何通过冒泡排序进行排序的,并且我知道对于这个特定的数组,要对数组进行排序有 11 次替换。每次该方法递归运行时,我都可以打印出所有交换次数,但是对于我的一生,我无法将这些数字分组到一个数组中,因此我可以添加它们并显示 11,任何见解都会很棒.我已经在 python 中完成了解决方案,它工作正常,我只想知道是否有一种方法可以将这些数字组合在一起,因为该方法正在递归运行。提前致谢。

【问题讨论】:

    标签: arrays ruby algorithm sorting recursion


    【解决方案1】:

    你也可以不用全局变量:

    def bubble_sort(a, swap_sum = 0)
      something_changed = false
      a[0...-1].each_with_index do |num, i|
        if a[i] > a[i + 1]
          a[i], a[i + 1] = a[i + 1], a[i]
          something_changed = true
          swap_sum += 1
        end
      end
      something_changed ? bubble_sort(a, swap_sum) : swap_sum
    end
    
    arr = [50, 60, 70, 20, 30, 10]
    bubble_sort(arr) #=> 11
    

    【讨论】:

    • 很好的修改添加它作为参数,确实不需要全局数组。
    【解决方案2】:
    $count = []
    def bubble_sort(a)
    something_changed = false
    swap = 0 
    a[0...-1].each_with_index do |num, i|
      if a[i] > a[i + 1]
         a[i], a[i + 1] = a[i + 1], a[i]
         something_changed = true
         swap += 1
      end
    end
    bubble_sort(a)  if something_changed
    $count << swap
    return $count.inject(:+)
    end
    arr = [50, 60, 70, 20, 30, 10]
    p bubble_sort(arr) # 11
    

    没关系,原来我是在我设置的全局变量上使用 p 而不是 return(我之前尝试过的东西,上面的问题中没有显示)。现在我可以只显示替换的数量。希望这可以帮助某人。感谢您的宝贵时间。

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 2012-05-28
      • 1970-01-01
      • 2013-10-09
      • 2021-02-06
      相关资源
      最近更新 更多