I'm trying to learn basic algorithms which are typically taught in an introduction to CS course, which is usually taught in a compiled language like Java. However, I want to focus on JavaScript, so I wrote the algorithms in JavaScript and encapsulated them into a library.
I'm looking for feedback on the efficiency of my implementations (bubbleSort, selectionSort, insertionSort
):
/***************************************************************************************************
**ALGORITHMS
***************************************************************************************************/
(function () {
"use strict";
var $A,
$P = {};
(function manageGlobal() {
if (window.$A && window.$A.pack) {
$A = window.$A;
$A.pack.algo = true;
}
}());
$P.swap = function (arr, i, j) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};
// checks to see if sorted
$P.isSorted = function (arr) {
var index_outer,
length = arr.length;
for (index_outer = 1; index_outer < length; index_outer++) {
if (arr[index_outer - 1] > arr[index_outer]) {
return false;
}
}
return true;
};
// repeatedly orders two items ( a bubble ) at a time
$P.bubbleSort = function (arr) {
var index_outer,
index_inner,
swapped = false,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
swapped = false;
for (index_inner = 0; index_inner < length - index_outer; index_inner++) {
if (arr[index_inner] > arr[index_inner + 1]) {
$P.swap(arr, index_inner, index_inner + 1);
swapped = true;
}
}
if (swapped === false) {
break;
}
}
return arr;
};
// repeatedly finds minimum and places it the next index
$P.selectionSort = function (arr) {
var index_outer,
index_inner,
index_min,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
index_min = index_outer;
for (index_inner = index_outer + 1; index_inner < length; index_inner++) {
if (arr[index_inner] < arr[index_min]) {
index_min = index_inner;
}
}
if (index_outer !== index_min) {
$P.swap(arr, index_outer, index_min);
}
}
return arr;
};
// repeatedly places next item in correct spot using a "shift"
$P.insertionSort = function (arr) {
var index_outer,
index_inner,
value,
length = arr.length;
for (index_outer = 0; index_outer < length; index_outer++) {
value = arr[index_outer];
for (index_inner = index_outer - 1; (index_inner >= 0 && (arr[index_inner] > value));
index_inner--) {
arr[index_inner + 1] = arr[index_inner];
}
arr[index_inner + 1] = value;
}
return arr;
};
// module complete, release to outer scope
$A = $A.extendSafe($A, $P);
}());