Sort using a custom comparator: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 64: Line 64:
==[[Python]]==
==[[Python]]==
[[Category:Python]]
[[Category:Python]]
'''Interpreter''': 2.4.3
'''Interpreter''': 2.5
<pre>
def mycmp(s1, s2):
def mycmp(s1, s2):
d = len(s2) - len(s1)
d = len(s2) - len(s1)
if d:
return d
return d if d else cmp(s1, s2)

return cmp(s1, s2)
strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
print sorted(strings, cmp=mycmp)
strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]

strings.sort(mycmp)
# Alternative with decoration, unfit for very long lists:
print sorted(strings, key=lambda s: (-len(s), s))
</pre>

Revision as of 21:34, 30 January 2007

Task
Sort using a custom comparator
You are encouraged to solve this task according to the task description, using any language you may know.

Sort an array (or list) of strings in order of descending length, then in ascending lexicographic order. Use a sorting facility provided by the language/library, combined with your own callback comparison function.

C

Compiler: GCC 4.0.1

Platform: BSD

#include <stdlib.h>
#include <strings.h>

int mycmp(const void *s1, const void *s2)
{
    int d;
    const char *l = *(const char **)s1, *r = *(const char **)s2;
    if (d = strlen(r) - strlen(l))
        return d;
    return strcasecmp(l, r);
}

int main()
{
    char *strings[8] = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"};
    qsort(strings, 8, sizeof(char *), mycmp);
}

Haskell

Interpreter: GHCi

import List
import Char

mycmp s1 s2 = case compare (length s2) (length s1) of
                 EQ -> compare (map toLower s1) (map toLower s2)
                 x  -> x

strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
sorted = sortBy mycmp strings

Perl

Interpreter: perl 5.8.6

sub mycmp { length $b <=> length $a or lc $a cmp lc $b }

@strings = ("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
@sorted = sort mycmp @strings;

PHP

Interpreter: PHP 4.4.4 CLI

<?php
function mycmp($s1, $s2)
{
    if ($d = strlen($s2) - strlen($s1))
        return $d;
    return strcasecmp($s1, $s2);
}

$strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted");
usort($strings, "mycmp");
?>

Python

Interpreter: 2.5

def mycmp(s1, s2):
    d = len(s2) - len(s1)
    return d if d else cmp(s1, s2)

strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
print sorted(strings, cmp=mycmp)

# Alternative with decoration, unfit for very long lists:
print sorted(strings, key=lambda s: (-len(s), s))