Scientific Calculator

(public) silentmatt/sort

By silentmatt Matthew Crumley

Sort a list, optionally with a custom ordering function. It's a bubble sort so don't use it in real code.

Tagged: algorithms

// order(a, b) should return a negative number if "a" should come before "b", a positive number if "a" should come after "b", or zero if they should be considered equal.
var Sort = function(list, order) {
    order = (order or :-); // That's not a smiley - ":-" is the the subtract function
    var i = 0;
    while (i < len list) -> (
        var j = i + 1;
        while (j < len list) -> (
            if (order(list[i], list[j]) > 0) -> (
                var temp = list[i];
                list[i] = list[j];
                list[j] = temp;
            );
            j += 1;
        );
        i += 1;
    );
    list;
};

// Sort([5, 2, 4, 3, 1, 0]) -> [0,1,2,3,4,5]

// This is exactly the same:
// Sort([5, 2, 4, 3, 1, 0], :-) -> [0,1,2,3,4,5]

// Sorting in reverse: "(:- . :-)" is the same as "function(a, b) { -(a - b) }"
// Sort([5, 2, 4, 3, 1, 0], (:- . :-)) -> [5,4,3,2,1,0]

spam? | offensive?

0 Comments

Sign in to leave a comment