Ruby中的Quicksort,Pivot是第一个元素

时间:2017-04-01 21:57:52

标签: ruby quicksort

这种方法永远不会结束......陷入连续循环。但是,我不明白为什么。 有人可以为我指出这一点。 我们的想法是做好一切。数组完全排序后,返回数组。

def quicksort(array, start=0, finish=array.size-1)
  return array if start >= finish
  pivot_index = start
  pivot_value = array[pivot_index]
  i = pivot_index + 1     # this sets apart the less than and greater than
  j = i                   # this sets apart the section that has/hasn't been evaluated

  # evaluate the pivot to the range of elements
  while j <= finish

    # if pivot > element being evaluated, put the evaluted elements inside "less than" section
    if array[pivot_index] > array[j]
      array[i], array[j] = array[j], array[i]
      i += 1
    end
    j += 1
  end

  # swap the pivot with the right-most element in the "less than" section
  array[pivot_index], array[i-1] = array[i-1], array[pivot_index]
  new_pivot_index = array.index(pivot_value)

  # sort to the right of the pivot
  unless new_pivot_index + 1 >= finish
    start = new_pivot_index + 1
    quicksort(array, start, finish)
  end

  # sort to the left of the pivot
  unless new_pivot_index == 0
    finish = new_pivot_index - 1
    start = 0
    quicksort(array, start, finish)
  end
  return array
end

1 个答案:

答案 0 :(得分:0)

事实证明,我只需要删除一些阻止基本案例被调用的除非语句。

答案如下。

def quicksort(array, start=0, finish=array.size-1)
  return if start >= finish
  pivot_index = start
  pivot_value = array[pivot_index]
  i = pivot_index + 1     # this sets apart the less than and greater than
  j = i                   # this sets apart the section that has/hasn't been evaluated

  # evaluate the pivot to the range of elements
  while j <= finish

    # if pivot > element being evaluated, put the evaluted elements inside "less than" section
    if array[pivot_index] > array[j]
      array[i], array[j] = array[j], array[i]
      i += 1
    end
    j += 1
  end

  # swap the pivot with the right-most element in the "less than" section
  array[pivot_index], array[i-1] = array[i-1], array[pivot_index]
  new_pivot_index = array.index(pivot_value)

  # sort to the right of the pivot
  quicksort(array, new_pivot_index + 1, finish)

  # sort to the left of the pivot
  quicksort(array, start, new_pivot_index - 1)
  return array
end