Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do stable sort?

How do I stably sort an array? The value I want to sort by can have a lot of duplicates, and I'm not sure which sort algorithm ruby uses. I'm thinking insertion sort would have worked best for me.

Example:

a = [[:a, 0], [:b, 1], [:c, 0], [:d, 0]]
a.sort_by { |x, y| y }  # => [[:a, 0], [:d, 0], [:c, 0], [:b, 1]]

Looking for

[[:a, 0], [:c, 0], [:d, 0], [:b, 1]]
like image 537
Karan Verma Avatar asked Feb 21 '14 06:02

Karan Verma


People also ask

How do you make a sorting algorithm stable?

Some in-place unstable sorting algorithms can be made stable by altering their implementation to use extra space. If you use this kind of alteration, the algorithm's implementation will become stable, but it will no longer be in-place.

What is stable sorting method?

What is a stable sorting algorithm? A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input data set. Formally stability may be defined as, how the algorithm treats equal elements.

What is stable sort example?

Several common sorting algorithms are stable by nature, such as Merge Sort, Timsort, Counting Sort, Insertion Sort, and Bubble Sort. Others such as Quicksort, Heapsort and Selection Sort are unstable.

Is sort () in C++ is stable sort?

sort() function usually uses Introsort. Therefore, sort() may preserve the physical order of semantically equivalent values but can't be guaranteed. stable_sort() function usually uses mergesort. Therefore, stable_sort() preserve the physical order of semantically equivalent values and its guaranteed.


1 Answers

Put the key that you originally wanted to sort by and the index into an array, and sort by that.

a.sort_by.with_index { |(x, y), i| [y, i] }
  # => [[:a, 0], [:c, 0], [:d, 0], [:b, 1]]
like image 152
sawa Avatar answered Sep 18 '22 17:09

sawa