Sorting

From Rosetta Code
Revision as of 08:07, 23 January 2007 by rosettacode>Markvp
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"

C++

 #include <algorithm>
 // sort an array
 int arr[] = { 3, 8, 5, 2, 9 };
 int arr_length = sizeof(arr)/sizeof(arr[0]);
 std::sort(arr, arr+arr_length);
 // sort a std-vector
 std::vector<int> vec;
 vec.push_back(5);
 vec.push_back(4);
 vec.push_back(7);
 vec.push_back(1);
 std::sort(vec.begin(), vec.end());
 // Sort an array in a custom way with a function.
 // This also works on std-vectors.
 // Note: of course the function is_bigger should be outside our function.
 bool is_bigger(int a, int b)
 {
   // note: for equal elements it should return false
   return a>b;
 }
 std::sort(arr, arr+arr_length, is_bigger);
 // Sort an array in a custom way with a function object.
 // This has the advantage that you can give a state to the sorting object.
 // This also works on std-vectors.
 // Note: the struct compare_modulo should be outside our function.
 struct compare_modulo
 {
   int mod;
   compare_modulo(int m): mod(m) {}
   bool operator()(int a, int b) const
   {
     // note: for equal elements it should return false
     return (a%mod)<(b%mod);
   }
 }
 std::sort(arr, arr+arr_length, compare_modulo(3));