I've been teaching myself Ruby this weekend. First of all, I am aware that there is a built-in sort function. I've written this code strictly as an exercise.
I have background primarily in C# and Javascript, so this is a change of pace for me.
If you are a seasoned professional with a lot of Ruby experience, my code will probably make your hair stand on end, so please advise me how to do this the right way in case I'm ever sitting next to you writing Ruby code.
The code appears to work, but I'll bet that the convention that I'm used to using is not the best way to get things done in Ruby.
class Array
@@swap = lambda {|a, i0, i1|
x = a[i0]
a[i0] = a[i1]
a[i1] = x
# puts "Swapping elements at position #{i0} and #{i1}"
# puts a.inspect()
}
@@recurse = lambda {|a, iStart, iEnd|
# puts "iStart = #{iStart}, iEnd = #{iEnd}, a=#{a.inspect()}"
# base case
return if (iStart == iEnd)
pivot = a[iEnd]
i = iStart # iterator to count over the array
j = iStart # the index of the last element less than the pivot
while i < iEnd
if a[i] < pivot
@@swap.call(a, i, j)
j += 1
end #if
i += 1
end #while
# Put the pivot element after the last element less than the pivot element
@@swap.call(a, j, iEnd)
# Recurse over the elements less than the pivot and the elements greater than the pivot
thread0 = Thread.new() { @@recurse.call(a, iStart, j - 1) if j != iStart }
.join()
thread1 = Thread.new() { @@recurse.call(a, j + 1, iEnd) if j != iEnd }
.join()
}
def quickSort()
@@recurse.call(self, 0, self.length() - 1)
end #quickSort
end
a = []
i = 0
until i === 1000
a.push(i)
i += 1
end
a.shuffle()
a.quickSort()
errorFound = false
i = 0
until i === 1000
errorFound = true unless (i === a[i])
i += 1
end
puts 'All sorted' unless errorFound
puts 'Error' if errorFound