You are viewing a single comment's thread. Return to all comments →
Full example in Ruby, using implementation from the previous challenges:
def insertion_sort(arr) ops = 0 i = 1 while (i < arr.length) if arr[i] < arr[i - 1] value = arr[i] j = i-1 while (j >= 0 && value < arr[j]) arr[j+1] = arr[j] ops += 1 j -= 1 end arr[j+1] = value end i += 1 end ops end def partition_lomuto(arr, lo, hi) pivot = arr[hi] i = lo - 1 lo.upto(hi) do |j| if arr[j] <= pivot i += 1 arr[i], arr[j] = arr[j], arr[i] end end [i, (i - lo + 1)] end def quicksort(arr, lo, hi) return 0 unless lo >= 0 && hi >= 0 && lo < hi pivot, ops_part= partition_lomuto(arr, lo, hi) quicksort(arr, lo, pivot - 1) + quicksort(arr, pivot + 1, hi) + ops_part end _n = gets.strip.to_i arr = gets.rstrip.split.map(&:to_i) puts insertion_sort(arr.clone) - quicksort(arr, 0, arr.length - 1)
Seems like cookies are disabled on this browser, please enable them to open this website
Running Time of Quicksort
You are viewing a single comment's thread. Return to all comments →
Full example in Ruby, using implementation from the previous challenges: