lib/manager/sort.rb
# Sample implementation of quicksort and mergesort in ruby
# Both algorithm sort in O(n * lg(n)) time
# Quicksort works inplace, where mergesort works in a new array
Sample implementation of quicksort and mergesort in ruby
Both algorithm sort in O(n * lg(n)) time
Quicksort works inplace, where mergesort works in a new array
Sample implementation of quicksort and mergesort in ruby Both algorithm sort in O ( n * lg ( n )) time Quicksort works inplace where mergesort works in a new array
def quicksort(array, from=0, to=nil)
    if to == nil
        to = array.count - 1
    end
    if from >= to
        return
    end
    pivot = array[from]
    min = from
    max = to
    free = min
    while min < max
        if free == min 
            if array[max] <= pivot 
                array[free] = array[max]
                min += 1
                free = max
            else
                max -= 1
            end
        elsif free == max 
            if array[min] >= pivot 
                array[free] = array[min]
                max -= 1
                free = min
            else
                min += 1
            end
        else
            raise "Inconsistent state"
        end
    end
    array[free] = pivot
    quicksort array, from, free - 1
    quicksort array, free + 1, to
end
def quicksort ( array , from = 0 , to = nil ) if to == nil to = array . count - 1 end if from >= to return end pivot = array [ from ] min = from max = to free = min while min < max if free == min if array [ max ] <= pivot array [ free ] = array [ max ] min += 1 free = max else max -= 1 end elsif free == max if array [ min ] >= pivot array [ free ] = array [ min ] max -= 1 free = min else min += 1 end else raise "Inconsistent state" end end array [ free ] = pivot quicksort array , from , free - 1 quicksort array , free + 1 , to end
Sample implementation of quicksort and mergesort in ruby
Both algorithm sort in O(n * lg(n)) time
Quicksort works inplace, where mergesort works in a new array
Sample implementation of quicksort and mergesort in ruby Both algorithm sort in O ( n * lg ( n )) time Quicksort works inplace where mergesort works in a new array
# Sort the whole array, by default # Done sorting # Take a pivot value, at the far left # Min and Max pointers # Current free slot # Evaluate array[max] # Smaller than pivot, must move # Evaluate array[min] # Bigger than pivot, must move
array
<not_specific>
from
<not_specific>
to
<not_specific>