Ruby Program to Implement Quick Sort

Ruby Program to Implement Quick Sort

Sorting is an essential part of programming that allows us to organize data efficiently. Among the many sorting algorithms, Quick Sort is one of the most powerful and widely used. Unlike simpler algorithms like Bubble Sort or Insertion Sort, Quick Sort uses a divide-and-conquer strategy to sort data. It works by selecting a “pivot” element, partitioning the array into smaller and larger elements, and then recursively sorting these partitions. This makes Quick Sort both fast and efficient, even for large datasets.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Quick Sort is used in many real-world applications, from database indexing to searching algorithms and even in software where high performance is crucial. Learning Quick Sort in Ruby helps beginners understand recursion, array manipulation, and efficient algorithm design. In this article, we will explore multiple ways to implement Quick Sort, including standard recursion, descending order sorting, and iterative approaches. By the end, you will understand both the logic and practical implementation of Quick Sort in Ruby.

Program 1: Quick Sort Using Recursion

This first program demonstrates the classic recursive approach to Quick Sort, which is the most common and beginner-friendly way to implement it.

# Program 1: Quick Sort using recursion
def quick_sort(array)

  return array if array.length <= 1

  pivot = array[array.length / 2]
  left = array.select { |x| x < pivot }
  middle = array.select { |x| x == pivot }
  right = array.select { |x| x > pivot }

  quick_sort(left) + middle + quick_sort(right)

end

numbers = [33, 10, 55, 71, 29, 3, 18]

sorted_array = quick_sort(numbers)

puts "Sorted array: #{sorted_array}"

In this program, the array is split into three parts: elements smaller than the pivot, elements equal to the pivot, and elements larger than the pivot. The recursive calls sort the smaller and larger partitions. This approach is useful for beginners because it clearly shows how recursion and partitioning work together to sort an array. You can see how smaller problems combine to solve the bigger sorting problem step by step.

Program 2: Quick Sort in Descending Order

Quick Sort can be easily adapted to sort data in descending order. This helps beginners understand that modifying the comparison logic can change the order of sorting.

# Program 2: Quick Sort in descending order
def quick_sort_desc(array)

  return array if array.length <= 1

  pivot = array[array.length / 2]
  left = array.select { |x| x > pivot }
  middle = array.select { |x| x == pivot }
  right = array.select { |x| x < pivot }

  quick_sort_desc(left) + middle + quick_sort_desc(right)

end

numbers = [40, 12, 5, 80, 25]

sorted_array = quick_sort_desc(numbers)

puts "Sorted array (descending): #{sorted_array}"

Here, the comparison is reversed, so larger elements go to the left partition and smaller elements go to the right. This demonstrates that the core Quick Sort logic remains the same while producing different results. Beginners can see that changing one simple condition can give you flexible sorting behavior.

Program 3: Quick Sort with In-Place Partitioning

This variation demonstrates Quick Sort using in-place partitioning, which is more memory-efficient because it avoids creating multiple arrays.

# Program 3: Quick Sort using in-place partitioning
def quick_sort_in_place(array, low = 0, high = array.length - 1)

  if low < high
    pi = partition(array, low, high)

    quick_sort_in_place(array, low, pi - 1)
    quick_sort_in_place(array, pi + 1, high)

  end

  array

end

def partition(array, low, high)

  pivot = array[high]
  i = low - 1

  for j in low...high

    if array[j] <= pivot
      i += 1
      array[i], array[j] = array[j], array[i]
    end

  end

  array[i + 1], array[high] = array[high], array[i + 1]
  i + 1

end

numbers = [24, 17, 85, 13, 9, 54]

sorted_array = quick_sort_in_place(numbers)

puts "Sorted array: #{sorted_array}"

In this approach, elements are swapped in place, which avoids extra memory usage from creating new arrays. Beginners will find this useful because it demonstrates a more efficient implementation of Quick Sort, suitable for large datasets. It also reinforces the concept of partitioning and how elements move around a pivot to achieve order.

Program 4: Quick Sort for Strings

Quick Sort can also sort strings alphabetically. This program demonstrates sorting an array of strings in ascending order.

# Program 4: Quick Sort for strings
def quick_sort(array)

  return array if array.length <= 1

  pivot = array[array.length / 2]
  left = array.select { |x| x < pivot }
  middle = array.select { |x| x == pivot }
  right = array.select { |x| x > pivot }

  quick_sort(left) + middle + quick_sort(right)

end

words = ["banana", "apple", "grape", "kiwi", "orange"]

sorted_words = quick_sort(words)

puts "Sorted words: #{sorted_words}"

This example is particularly useful for beginners who want to sort text data. The logic remains the same as numerical Quick Sort, but comparisons are done alphabetically. It shows that Quick Sort is flexible and can handle different types of data, making it a versatile tool for various applications.

Frequently Asked Questions (FAQ)

Quick Sort often raises questions among beginners. Here are some common queries:

Q1: What is the time complexity of Quick Sort?
Quick Sort has an average-case time complexity of O(n log n). In the worst case, it can be O(n²), but this is rare if a good pivot strategy is used.

Q2: Is Quick Sort stable?
Quick Sort is not stable by default because it may change the relative order of equal elements during partitioning.

Q3: Can Quick Sort handle large datasets?
Yes, Quick Sort is efficient and works well for large datasets, especially when implemented with in-place partitioning.

Q4: When should I use Quick Sort over other algorithms?
Quick Sort is ideal when you need fast sorting with minimal extra memory and when performance is important. It is widely used in real-world applications because of its efficiency.

Conclusion

In this article, we explored how to implement Quick Sort in Ruby using recursion, descending order, in-place partitioning, and sorting strings. Quick Sort is a fast, efficient, and versatile sorting algorithm that helps beginners understand recursion, array manipulation, and divide-and-conquer strategies. By practicing these examples, you will gain confidence in implementing efficient sorting algorithms and handling both numbers and strings. Quick Sort is a foundational algorithm, and mastering it gives you a strong base for exploring more advanced algorithms in Ruby and programming in general.

Scroll to Top