2017-04-01 42 views
0

该方法永不结束......陷入连续循环。但是,我不明白为什么。 有人可以为我指出这一点。 这个想法是要做的一切。一旦数组完全排序后,返回数组。Ruby中的快速排序第一个元素是枢轴

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 
+0

是否就地快速排序实现通常从数组中间选择pivot元素? –

+0

我正在做多种格式。第一个元素,最后一个元素,随机元素。但是,现在我只是试图实现第一个元素 – Doughtz

回答

0

事实证明我只是需要删除一些阻止基本情况被调用的except语句。

答案在下方。

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 
相关问题