Ruby quick sort algorithm introduction

Quick sort (Quick Sort) is a comparison-based sorting algorithm and one of the most commonly used sorting algorithms. Its idea is to select a reference element, divide the sequence to be sorted into two sub-sequences, make all elements in the left sequence less than or equal to the reference element, and all elements in the right sequence are greater than or equal to the reference element, and then divide the left and right sub-sequences Sequences are sorted recursively, and finally an ordered sequence is obtained.

The time complexity of the quick sort algorithm is O(nlogn), which has high efficiency and is widely used in various sorting scenarios.

The following is a sample code for implementing the quicksort algorithm in Ruby:

```ruby
def quick_sort(arr)
  return arr if arr.length <= 1 # If the length of the array is less than or equal to 1, return the array directly
  pivot = arr.sample # select a reference element
  left, right = arr.partition { |ele| ele < pivot } # Divide into two left and right subsequences
  quick_sort(left) + quick_sort(right) # Recursively sort the left and right subsequences and merge them into an ordered sequence
end

# 示例
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_arr = quick_sort(arr)
puts sorted_arr.inspect # [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```

In the above code, we first judge whether the length of the array is less than or equal to 1, and if so, return the array directly. Otherwise, we choose a pivot element, use the `partition` method to divide the array into left and right subsequences, and recursively sort the left and right subsequences. Finally, we merge the sorted left and right subsequences into an ordered sequence and return the result.

In this implementation, we use Ruby's built-in `partition` method, which can divide an array into two subsequences based on a given condition. Specifically, we use the `partition` method in the form of a block to put the elements in the array that are smaller than the reference element into the left subsequence, and the elements greater than or equal to the reference element into the right subsequence, thus realizing the division operation.

Additionally, we used the `sample` method to select the benchmark element. This method can randomly select an element from the array as the reference element, which avoids the problem that the efficiency of the quick sort algorithm is reduced by selecting the largest or smallest element.

To sum up, this is a simple and efficient Ruby implementation of the quicksort algorithm sample code.

Guess you like

Origin blog.csdn.net/q6115759/article/details/130421208