The stability of a sorting algorithm

The stability of a sorting algorithm is the property that the elements that compare to be equal preserve their original order after sorting. For example, if we have an array of objects containing the ID number and the age of some people and we want to sort them in increasing order of age, a stable sorting algorithm will preserve the original order of the people with the same age. This can be helpful if we are trying to sort multiple times. For example, if we want the IDs to be in increasing order for people with the same age, we can first sort the array by ID and then sort it again by age. If the sorting algorithm is stable, it will ensure that the final sorted array is in increasing order of age, and for the same age, it is in increasing order of ID. Of course, this effect can also be achieved by having a more complex comparison with a single sorting operation. Quicksort is not stable, but mergesort is. It is easy to see why mergesort is stable. During merging, we preserve the order, that is, values from the left half precede values from the right half when they compare as equal.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset