xakepp35
xakepp35

Reputation: 3242

What are sorting algorithms that does not break previous sort

Imagine i have an array of elements with name and type. First i run a quicksort array by name. But then i want to run a sort by type, so in each type class elements will remain sorted by name. Quicksort is not doing that, it can reorder. And Bubble sort is too slow. What good algorithm should i use for that? And how it that property of sorting function is called? (that preserves order of same elements)

Upvotes: 0

Views: 88

Answers (1)

amit
amit

Reputation: 178491

This property is called stable sort. There are several such algorithms, merge sort is one of the most familiar out of them.

P.S. Another alternative is to use a single sort, but use a compound comparator, that first compares by the "primary" criteria (type in your case), and if types are equal, by "secondary" criteria (name in your case). This way, you will get the output sorted in the order you are expecting using a single sort.

Upvotes: 3

Related Questions