Perl: Sort Unstable

By Xah Lee. Date:

One piece of history. Perl's “sort” function used to be unstable. That is, it messes up your original order.

Here's one of my old note in perl:

# -*- coding: utf-8 -*-

# date: 2005
# perl's sort mess up the original order. Fixed sometimes after 2005.

use Data::Dumper;
$Data::Dumper::Indent=0;

@aa = ([4,3],[1,3],[3,28],[2,3],[5,2],[6,1]);

@bb = sort {$a->[1] <=> $b->[1]} @aa;

print Dumper \@bb;

It sorts list of pairs by their second element. Normally, the first 2 elements [4,3],[1,3] should remain in that order. But if it's unstable, it changes their order.

Here's verification. From perl 5.8.6 history file. Perl 5.8.6 is released on .

Although Perl has promised since version 5.8 that sort() would be stable, the two cases sort {$b cmp $a} and sort {$b <=> $a} could produce non-stable sorts. This is corrected in perl5.8.6.

from http://perldoc.perl.org/perl586delta.html

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email