To do selection sort using a BoundArray, add a script tag to include boundarray.js and an empty list with an id. This uses an unordered list with the id "names":
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>selectionsort</title> <!-- Date: 2008-11-07 --> <script src="../../src/boundarray.js" type="text/javascript"></script> <script src="../../lib/jquery-1.2.6.js" type="text/javascript"></script> <script src="selectionsort.js" type="text/javascript" charset="utf-8"></script> </head> <body> <ul id="names" style="list-style-type: none;"><li></li></ul> </body>
This html file is included in the iframe to the right.
Now in our JavaScript file, we can bind to that list with var names = new BoundArray(array, 'names');. From then on, we can use names like we would any other JavaScript array and it's changes will be mirrored in the list with id "names".
Note how the selectionsort function manipulates the names array, but does none of the code to keep the HTML list in sync. All of this glue code is handled by BoundArray.
var selectionsort = function (array, delay) {
// Done only using recursive iteration, because I want to delay between steps.
var i = 0;
(function step() {
var min_at = i;
var j, tmp;
for (j=i+1; j<array.length; j++) {
if (array[j] < array[min_at]) {
min_at = j;
}
}
tmp = array[i];
array[i] = array[min_at];
array[min_at] = tmp;
i++;
if (i<array.length-1) {
setTimeout(step, delay);
}
})();
};
var try_selectionsort = function () {
var array = ['jessica', 'ashley', 'brittany', 'amanda', 'stephanie',
'jennifer', 'samantha', 'sarah', 'megan', 'lauren', 'elizabeth',
'emily', 'amber', 'nicole', 'rachel', 'kayla', 'heather', 'melissa',
'rebecca', 'michelle', 'danielle', 'courtney', 'tiffany', 'chelsea',
'christina', 'katherine', 'kelsey', 'maria', 'laura', 'jasmine'];
var names = new BoundArray(array, 'names');
selectionsort(names,1000);
};
window.onload = try_selectionsort;