# Re: stable sort\_by?

**URL:** <https://www.ruby-forum.com/t/re-stable-sort-by/100087>\
**Category:** Ruby\
**Created:** [December 13, 2005, 1:16pm UTC](https://www.ruby-forum.com/t/re-stable-sort-by/100087 "2005-12-13T13:16:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![KroegerS\_Simon\_Sext](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@KroegerS\_Simon\_Sext](https://www.ruby-forum.com/u/KroegerS_Simon_Sext)\
**Post date:** [December 13, 2005, 1:16pm UTC](https://www.ruby-forum.com/t/re-stable-sort-by/100087/1 "2005-12-13T13:16:18Z")

</div>

> > 
> 
> … So, in this case [1,“c”] and [1,“b”] are equivalent, and  
> their order  
> is un-important …

From [Sorting algorithm - Wikipedia](http://en.wikipedia.org/wiki/Stable_sort) :

Stability: stable sorting algorithms maintain the relative order  
of records with equal keys (i.e. values). That is, a sorting algorithm  
is stable if whenever there are two records R and S with the same  
key and with R appearing before S in the original list, R will appear  
before S in the sorted list.

cheers

Simon

---

<div class="post-metadata">

**Author:** ![KroegerS\_Simon\_Sext](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/57b2e6/32.png) [@KroegerS\_Simon\_Sext](https://www.ruby-forum.com/u/KroegerS_Simon_Sext)\
**Post date:** [December 13, 2005, 2:25pm UTC](https://www.ruby-forum.com/t/re-stable-sort-by/100087/2 "2005-12-13T14:25:31Z")

</div>

Kroeger, Simon (ext) wrote:

> > > 
> > 
> > … So, in this case [1,“c”] and [1,“b”] are equivalent, and  
> > their order  
> > is un-important …
> 
> From [Sorting algorithm - Wikipedia](http://en.wikipedia.org/wiki/Stable_sort) :
> 
> Stability: stable sorting algorithms maintain the relative order  
> of records with equal keys (i.e. values). That is, a sorting algorithm  
> is stable if whenever there are two records R and S with the same  
> key and with R appearing before S in the original list, R will appear  
> before S in the sorted list.

It’s pretty easy to transform every sorting operation into a stable one:

orig:  
enum.sort\_by {|x| calculate\_key(x)}

stable:  
i=0  
enum.sort\_by {|x| [calculate\_key(x), i+=1]}

Kind regards

```
robert

```
