9.8Sorting on Several Keys
Covers IGNOU MCS-208 §9.6
Real records are often sorted by more than one field: students by class, then by roll number; cards by suit, then by face value. The first key is the primary (most significant) key; ties are broken by the secondary key. There are two general strategies.
MSD and LSD
- MSD (most significant digit/key first): sort by the primary key into piles, then sort each pile separately by the secondary key, and so on.
- LSD (least significant digit/key first): sort the whole file by the least significant key, then by the next key, …, and finally by the primary key, using a stable sort for every pass except the first.
“Digit” here means “key”. MSD and LSD only decide the order of the passes; each pass may use any suitable sorting method (LSD needs a stable one).
| MSD | LSD | |
|---|---|---|
| First pass sorts by | Primary key | Least significant key |
| Later passes | Each pile separately | The whole file |
| Stability required | No | Yes (for every pass after the first) |
| Typical use | Sorting by a few keys, recursive splitting | Radix sort of numbers digit by digit, punched-card sorters |
Radix sort is the LSD method applied to the digits of numbers: sort by units digit, then tens, then hundreds, each time with a stable distribution into 10 piles. For numbers of digits it takes time, without any key comparisons.
Key takeaways
- Primary key decides the main order; secondary keys break ties.
- MSD: sort by the primary key into piles, then sort each pile.
- LSD: sort by the least significant key first, the primary key last, with stable sorts.
- Radix sort is LSD on digits: for base .
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Explain the MSD and LSD methods for sorting a deck of cards by suit and face value.
Show worked answer
MSD: first sort the 52 cards into 4 piles by suit (the most significant key); then sort each pile separately by face value (Ace to King); finally stack the piles in suit order. LSD: first sort all 52 cards into 13 piles by face value (the least significant key) and stack the piles in order; then sort the whole deck into 4 piles by suit using a stable method (e.g. dealing the cards in order onto the suit piles), so that within each suit the face-value order from the first pass is kept; stack the suit piles. Both give the deck ordered by suit and, within suits, by face value; LSD requires the second pass to be stable.