Sorting: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 23: Line 23:
#create a test array
#create a test array
ary=['Long','words','are','more','interesting','than','short','ones']
ary=['Long','words','are','more','interesting','than','short','ones']
ary.sort do |wx,wy|
ary.sort_by {|a| [-a.size,a]}
if wx.length==wy.length
wx <=> wy
else
wy.length <=> wx.length
end
end
# => ["interesting", "short", "words", "Long", "more", "ones", "than", "are"]
# => ["interesting", "short", "words", "Long", "more", "ones", "than", "are"]

Revision as of 22:37, 22 January 2007

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);


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"]