From: Mauricio Fernandez Date: 2006-02-07T18:17:41+09:00 Subject: Re: Feeling sharp? Sort an array subset in place. On Tue, Feb 07, 2006 at 05:28:21PM +0900, Michael Judge wrote: > Here's the situation: I have an array and I'd like to sort certain > elements in place -- without touching the others. > > Unsorted array contents: > 3 <-- sort me! > x > 1 <-- sort me! > y > 2 <-- sort me! > > Sorted array contents > 1 > x > 2 > y > 3 class Array def sort_subset! els, indices = [], [] each_with_index{|x,i| (els << x; indices << i) if yield(x) } els.sort.each_with_index{|x,i| self[indices[i]] = x} end end a = (0..10).sort_by{rand} a # => [1, 8, 2, 10, 3, 0, 5, 4, 9, 7, 6] a.sort_subset!{|x| x % 2 == 0} # => [0, 2, 4, 6, 8, 10] a # => [1, 0, 2, 4, 3, 6, 5, 8, 9, 7, 10] a.sort_subset!{|x| x % 2 == 1} # => [1, 3, 5, 7, 9] a # => [1, 0, 2, 4, 3, 6, 5, 8, 7, 9, 10] -- Mauricio Fernandez