Here is a little trick I came up with for sorting a subset of array elements in Ruby.
I needed to sort a subset of elements in an array while leaving the other elements in the positions they occupied.
The algorithm I used was to create a new array with just the items I want to sort. Sort the new array’s elements. Then you have the original array that contains all the elements and a second sorted array with just the items you are interested in. The original array and the sorted array both contain the same subset of items then you want sorted. So go through the original array and whenever you find one of the items you wanted to sort replace it with the next item from the sorted array.
Ruby array subset sort