2017-04-01 5 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

インプレースクイックソルトの実装では、通常、配列の中央からピボット要素を選択しないでください。 –

+0

私は複数のフォーマットでそれをやっています。最初の要素、最後の要素、ランダム要素。しかし、今私はただの要素を実装しようとしています – Doughtz

答えて

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 
関連する問題