Choose the last item as a pivot, partition smaller values to its left, then recurse on the two sides.

Algorithm

Basic Implementation

basic.rb
def partition(arr, low, high)
	pivot = arr[high]
	i = low - 1
	(low...high).each do |j|
		if arr[j] <= pivot
			i += 1
			arr[i], arr[j] = arr[j], arr[i]
		end
	end
	arr[i + 1], arr[high] = arr[high], arr[i + 1]
	i + 1
end

def quick_sort(arr, low, high)
	if low < high
		pivot_index = partition(arr, low, high)
		quick_sort(arr, low, pivot_index - 1)
		quick_sort(arr, pivot_index + 1, high)
	end
end

arr = [4, 1, 5, 2, 3]
quick_sort(arr, 0, arr.length - 1)
puts arr.inspect

The pinned first partition uses [4, 1, 5, 2, 3] with pivot 3. The diagrams track the boundary, swaps, and recursive ranges.

Step 1 - Choose the last value as pivot

The pivot is arr[4] = 3, and i starts just before the current range.

Initial partition state for [4, 1, 5, 2, 3].i0i1i2i3i441523j startspivot

Step 2 - Swap small values left

1 and 2 are <= pivot, so they move into the left partition.

After scanning values before the pivot: [1, 2, 5, 4, 3].i0i1i2i3i412543<= 3<= 3> 3> 3pivot

Step 3 - Place pivot, then recurse

Swapping pivot 3 into index 2 gives [1, 2, 3, 4, 5]; recurse on [1, 2] and [4, 5].

Pivot lands at index 2 and splits the remaining work.left rangepivotright range[1, 2]3 at i2[4, 5]quick_sort(0,1)fixedquick_sort(3,4)

Complexity

  • Time: O(n^2) worst, O(n log n) average
  • Space: O(log n) average call stack
  • Stable: no

Implementation notes

  • quick_sort(arr, low, high) mutates the same Ruby Array; it does not return a new sorted array.
  • The recursion guard is if low < high, so empty and one-element ranges stop without calling partition.
  • partition(arr, low, high) chooses the last slot as the pivot with pivot = arr[high].
  • i = low - 1 marks the end of the <= pivot side, and (low...high).each scans j up to but not including the pivot slot.
  • When arr[j] <= pivot, Ruby parallel assignment arr[i], arr[j] = arr[j], arr[i] swaps two array slots in place.
  • After the scan, arr[i + 1], arr[high] = arr[high], arr[i + 1] places the pivot at its final index and returns i + 1.
  • The trace for [4, 1, 5, 2, 3] keeps 4 and 5 on the right of pivot 3, swaps 1 and 2 left, then places 3 at index 2.
  • The replay then summarizes recursive calls on [1, 2] and [4, 5]; it does not include a separate bad-pivot degradation case.
  • puts arr.inspect prints the mutated array as [1, 2, 3, 4, 5].
pivot The final element is moved to the boundary between smaller and larger values.
partition One scan rearranges the current range before the recursive calls.