#The Quick Sort is a popular sorting algorithm, which has been discussed in detail, with examples and C code over here : Arrays and Sorting: Quick Sort ( with C Program source code). In this tutorial, we will take a quick look at the ruby implementation of Quick Sort.
#1
def partition arr, lo, hi
i,j = lo+1,hi
while true
i+=1 while arr[i] <= arr[lo] and i < hi
j-=1 while arr[j] > arr[lo] and j > lo
break if i>=j
arr[i], arr[j] = arr[j], arr[i] #swap
end
arr[lo], arr[j] = arr[j], arr[lo]
j
end
def quicksort arr, lo = 0, hi = nil
hi ||= arr.size - 1
return arr if hi <= lo
pivot = partition arr, lo, hi
quicksort arr, lo, pivot-1
quicksort arr, pivot+1, hi
end
#test
p quicksort [3,4,2,6,56,14,33,1,9,6] #[1, 2, 3, 4, 6, 6, 9, 14, 33, 56]
#2
def quickSort(arr,from,to)
return if from >= to
pivot = arr[from]
i = from
for j in (1+from)..to
if arr[j] < pivot
i = i + 1
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
end
end
quickSort(arr,from,i-1);
quickSort(arr,i+1,to);
end
original_array=[2,19,5,4,3,14,2]
puts "Sorted Array Using Quick Sort:"
quickSort(original_array,0,original_array.length - 1)
p original_array