From d2d79b0e3d84c0eb938990705a453b070529b698 Mon Sep 17 00:00:00 2001 From: Guhan M Date: Thu, 6 May 2021 17:07:18 +0530 Subject: [PATCH 1/2] Added Quick Sort in Ruby --- Ruby/QuickSort.rb | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Ruby/QuickSort.rb diff --git a/Ruby/QuickSort.rb b/Ruby/QuickSort.rb new file mode 100644 index 0000000..6ffb10b --- /dev/null +++ b/Ruby/QuickSort.rb @@ -0,0 +1,43 @@ +#!/usr/bin/env ruby + +# Run it from a terminal as a ruby script, with space separated numbers: +# ruby QuickSort 23 12 3 99 129 482 12 + +array = ARGV +array.map!(&:to_i) +puts 'Your unsorted numbers' +p array + +class QuickSort + class << self + def sort(array, first, last) + if first < last + partitionIndex = partition(array, first, last) + sort(array, first, partitionIndex-1) + sort(array, partitionIndex+1, last) + end + return array + end + + private + + def partition(array, first, last) + pivot = array[last] # Pivot + partitionIndex = first # Partition index + for i in first...last + if array[i] <= pivot + array[i], array[partitionIndex] = array[partitionIndex], array[i] # Swapping + partitionIndex += 1 + end + end + i += 1 + + array[i], array[partitionIndex] = array[partitionIndex], array[i] # Swapping + + return partitionIndex + end + end +end + +puts "\nNumbers sorted:" +p QuickSort.sort(array, 0, array.size-1) From 47296fca98e04f6f393d55cf7cf6478aee6c3a5d Mon Sep 17 00:00:00 2001 From: Guhan M Date: Thu, 6 May 2021 17:14:08 +0530 Subject: [PATCH 2/2] Added comment --- Ruby/QuickSort.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/Ruby/QuickSort.rb b/Ruby/QuickSort.rb index 6ffb10b..6662117 100644 --- a/Ruby/QuickSort.rb +++ b/Ruby/QuickSort.rb @@ -8,6 +8,7 @@ puts 'Your unsorted numbers' p array +# Quick Sort algorithm class QuickSort class << self def sort(array, first, last)