Sorting: Difference between revisions

From Rosetta Code
Content added Content deleted
(Add Ada version)
(purged, added links)
Line 1: Line 1:
For examples of how to use sorting functionality provided by a language, see:
{{task}}
* [[Sorting an Array of Integers]]
* [[Sorting Using a Custom Comparator]]


For complete implementations of various sorting algorithms, see [[:Category:Sorting Algorithms]].
Sort an Array of Strings, from large to small and lexicographic for Strings of equal length


{{stub}}
==[[Ada]]==
[[Category:Ada]]
'''Compiler:''' GCC 4.1.2

package String_Sorting is
type String_Access is access all String;
type String_Array is array (Positive range <>) of String_Access;
procedure Sort (Strings : in out String_Array);
-- From longer to shorter strings, lexicographic ascending order
-- for strings of equal length.
end String_Sorting;
with Bubble_Sort; -- see programming task Bubble Sort
package body String_Sorting is
function Equal (S1, S2 : String_Access) return Boolean is
begin
if S1 = null then
return S2 = null;
elsif S2 = null then
return False;
else
return S1.all = S2.all;
end if;
end Equal;
function Longer (S1, S2 : String_Access) return Boolean is
begin
if S1 = null then
return False;
elsif S2 = null then
return True;
elsif S1'Length = S2'Length then
return S1.all < S2.all;
else
return S1'Length > S2'Length;
end if;
end Longer;
procedure Bubble is new Bubble_Sort
(String_Access, Equal, Longer, Positive, String_Array);
procedure Sort (Strings : in out String_Array) is
begin
Bubble (Strings);
end Sort;
end String_Sorting;

==[[C plus plus|C++]]==
[[Category:C plus plus|C++]]

sort an array
#include <algorithm>
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 (this also works with std deque)
#include <algorithm>
#include <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 a std list
#include <list>
std::list<int> intlist;
intlist.push_back(5);
intlist.push_back(4);
intlist.push_back(7);
intlist.push_back(1);
intlist.sort();
Sort an array in a custom way with a function.
This also works on std-vectors and std deques.
Note: of course the function is_bigger should be outside our function.
#include <algorithm>
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 a list in a custom way with a function.
#include <list>
bool is_greater(int a, int b) { return a > b; }
int values[6] = { 11, 32, 53, 64, 45, 26 };
std::list<int> intlist(values, values+6);
intlist.sort(is_greater);

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.
#include <algorithm>
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));
Sort an array in a custom way with standard-supplied function objects
#include <algorithm>
#include <functional>

int arr[6] = { 2, 3, 7, 5, 13, 11 };
std::sort(arr, arr+6, std::greater<int>());

Sort an array in a stable way. This is different from the other sort in that equal elements stay in the same order as they were before sorting. This is a little slower. This has no use on int's of course, but it may be important with objects. You can also use this with std-vectors, and there is also a version that takes a third argument as the compare object, as above with std::sort. It can be demonstrated on ints with a custom sort function.
#include <algorithm>
bool has_smaller_trailing_digit(int i, int j) { return i%10 < j%10; }
int arr[] = { 13, 22, 39, 42, 59 };
int arr_length = sizeof(arr)/sizeof(arr[0]);
std::stable_sort(arr, arr+arr_length, has_smaller_trailing_digit);
This gives the order
22, 42, 13, 39, 59
that is, the trailing digits are in ascending order (that's what the custom function says), but the order did not change otherwise (e.g. 22 still comes before 42). An unstable sort could e.g. have given the result
42, 22, 13, 39, 59
which also has increasing trailing digits, but otherwise the order is arbitrary.

==[[Java]]==
[[Category:Java]]

Object[] sorted = new Object[] ("this", "that", "and", "the", "other");
Arrays.sort(sorted);

For custom sorting implement a Comparator

public class Foo {
private String foo;
public Foo(String f) { foo = f; }
public String getFoo() { return foo; }
}

Foo[] sorted = new Foo[] {new Foo("foo"), new Foo("bar")};
Arrays.sort(sorted, new Comparator<Foo>() {
public int compare(Foo f1, Foo f2) {
return f1.getFoo().compareTo(f2.getFoo());
}
});

==[[PHP]]==
[[Category:PHP]]

===Sorting an array while maintaining index association===
$array = array('a' => 'lemon', 'b' => 'orange', 'c' => 'banana');
asort($array);
print_r($array);

'c' => 'banana'
'a' => 'lemon'
'b' => 'orange'

===Sorting an array while maintaining key to data association===
$array = array('b' => 'orange', 'a' => 'lemon', , 'c' => 'banana');
asort($array);
print_r($array);

'a' => 'lemon'
'b' => 'orange'
'c' => 'banana'

===Sorting an array with "Natural" sorting===
$array = array('img2.jpg', 'img10.jpg', 'img1.jpg', 'img12.jpg');
natsort($array);
print_r($array);

img1.jpg, img2.jpg, img10.jpg, img12.jpg

'''Note''' If sort() had been used, it would have returned img1.jpg, img10.jpg, img12.jpg, img2.jpg.

==[[Perl]]==
[[Category: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]]==
[[Category:Python]]

'''Interpreter:''' Python 2.4

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

<!-- NOTE: a single sorted(words, key=len, reverse=True) won't produce the
desired results for strings of equal length -->
# 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))
# result: ['interesting', 'short', 'words', 'Long', 'more', 'ones', 'than', 'are']
# otherwise
words.sort(key=lambda word: (-len(word), word))

<!-- NOTE: this gives a solution like the C++ one: sorted([13, 22, 39, 42, 59], key=lambda n: n%10) -->

==[[Ruby]]==
[[Category:Ruby]]

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

==[[SAS]]==
[[Category:SAS]]

PROC SORT DATA=foo;
BY bar;
RUN;

==[[UNIX Shell]]==
[[Category: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"

Revision as of 11:50, 31 January 2007

For examples of how to use sorting functionality provided by a language, see:

For complete implementations of various sorting algorithms, see Category:Sorting Algorithms.


This page is a stub. It needs more information! You can help Rosetta Code by filling it in!