Skip to content Skip to sidebar Skip to footer

Javascript Sorting By Algorithm, Jquery Maybe

Okay, I am trying to create a sorting application but, its kinda busting my mind. Maybe because of thinking too much. What I wanted I want to sort values from an array, maybe usin

Solution 1:

Yes, setTimeout is a good idea if you want to "see" the algorithm's progress. However, setTimeout only accepts functions as arguments, so each iteration of the sorting algorithm has to be performed in a separate function. See the following code for an example (the code doesn't produce output in each iteration, instead it "animates" the swapping action - but I'm sure you can easily adjust this to fit your needs).

DEMO (JSFiddle)

var SORT = function(type, list, selector){
    var container, containerTr, animSteps = [];
    // Show all elements in the container
    var printArray = function(list){
        var str = ["<table>"], i = 0, l = list.length;
        for (i; i < l; ++i) {
            str.push("<tr><td>", list[i], "</td></tr>");
        }
        str.push("</table>");
        container.html(str.join(""));
    };
    // This is the interesting part... ;)
    var swap = function(list, i1, i2) {
        var tmp = list[i1];
        list[i1] = list[i2];
        list[i2] = tmp;
        // Add 3 functions foreach swapping action:
        //1. highlight elements, 2. swap, 3. remove highlight
        animSteps.push(function(){
            containerTr.eq(i1).add(containerTr.eq(i2)).addClass("highlight");
        }, function(){
            var tmp = containerTr.eq(i1).text();
            containerTr.eq(i1).text(containerTr.eq(i2).text());
            containerTr.eq(i2).text(tmp);
        }, function(){
            containerTr.eq(i1).add(containerTr.eq(i2)).removeClass("highlight");
        });
    };
    var animation = function(){
        // Execute all iteration functions one after another
        if (animSteps.length) {
            setTimeout(function(){
                animSteps.splice(0,1)[0]();
                animation();
            }, 250);
        }
    };

    // Collection of sorting algorithms
    var algorithms = {
        bubblesort: function(list) {
            for (var n = list.length; n > 1; --n) {
                for (var i = 0; i < n-1; ++i) {
                    if (list[i] > list[i+1]) {
                        swap(list, i, i+1);
                    }
                }
            }
        }
        // Add more algorithms using "swap" here...
    };

    if (algorithms[type] != undefined) {
        container = $(selector);
        printArray(list);
        containerTr = container.find("tr");
        algorithms[type](list);
        this.sorted = list;
        animation();
    }
};

// Usage:
var s = new SORT("bubblesort", [5,8,2,4,1,9,7,3,0,6], "#container");
console.log(s.sorted);    //the sorted array

Post a Comment for "Javascript Sorting By Algorithm, Jquery Maybe"