Sorting

From Rosetta Code
Revision as of 05:42, 23 January 2007 by 70.83.136.146 (talk)
Task
Sorting
You are encouraged to solve this task according to the task description, using any language you may know.

Sort an Array of Strings, from large to small and lexicographic for Strings of equal length

Perl

Interpeter: Perl

Numeric sort

my @sorted = sort {$a<=>$b} (3, 6, 4, 5, 2, 7, 1);

Alpha-Numeric sort

my @sorted = sort ('this', 'that', 'and', 'the', 'other');

Numeric sort or Alpha-Numeric sort if a numeric sort cannot be done

# note, this can be a oneliner
my @sorted = sort {
   ($a =~ /^\-?\d+\.?\d*$/ and $b =~ /^\-?\d+\.?\d*$/) ? $a <=> $b : $a cmp $b
} ('this', 'that', 'and', 'the', 'other', 3, 6, 4, 5, 2, 7, 1);

Python

Interpreter: Python 2.5

Python's lists have a method for in-place sorting; there's also a built-in sorted() method that can sort any iterable.

# create a sample list
words = ['Long', 'words', 'are', 'more', 'interesting', 'than', 'short', 'ones']

# order it and keep the result on another variable
sorted_words = sorted(words, key = lambda word: (-len(word), word))

# sorted_words: ['interesting', 'short', 'words', 'Long', 'more', 'ones', 'than', 'are']

Ruby

#create a test array
ary=['Long','words','are','more','interesting','than','short','ones']
ary.sort_by {|a| [-a.size,a]}
# => ["interesting", "short", "words", "Long", "more", "ones", "than", "are"]

UNIX Shell

words='Long words are more interesting than short ones'
sorted_words="$(
  for word in $words # doesn't work with ZSH since it won't do field splitting here
  do echo "$word"
  done | sort | \
    while read word
    do echo -n "$word "
    done
  echo
 )"
echo "$sorted_words"