Partager via


Classic Computer Science in JavaScript

Ah, remember the good ole college days where you had to code in CICS and Cobol? No? Um...okay I'm showing my age. Anyways, we all had to go through some of the basics of computer science at some point to understand specific algorithms and how sorting works and while we may want to forget some of those courses altogether, the stuff we learned is certainly applicable till this day.

Well, programmer extrodinaire Nicholas Zakas has started to compile a collection of JavaScript code that tackles many of the common approaches. For example, here's the classic bubble sort

 function swap(items, firstIndex, secondIndex){
    var temp = items[firstIndex];
    items[firstIndex] = items[secondIndex];
    items[secondIndex] = temp;
}
 
/**
* A bubble sort implementation in JavaScript. The array
* is sorted in-place.
* @param {Array} items An array of items to sort.
* @return {Array} The sorted array.
*/
function bubbleSort(items){

    var len = items.length,
        i, j, stop;

    for (i=0; i < len; i++){
        for (j=0, stop=len-i; j < stop; j++){
            if (items[j] > items[j+1]){
                swap(items, j, j+1);
            }
        }
    }
    
    return items;
}

He covers many different classic computer science paradigms, algorithms, and approaches and it's well worth the look, especially if you're a self-taught developer without a formal background in CS.

Comments

  • Anonymous
    June 12, 2011
    The comment has been removed

  • Anonymous
    June 13, 2011
    LOL! Yeah those were the days when you had to submit a job and then wait for the top of the hour to see the results. So you coded furiously to get that last bit in till 5 minutes before the top of the hour and "Boom!' error. Wait another hour. ;)

  • Anonymous
    June 14, 2011
    Error?  What is an error?  Not sure I have ever seen one of those ;-)