Live code: http://jsfiddle.net/fCUZC/
//INPUT ARRAY:
var input = [28,32,21,11,8,2,14,32,64];
//VARIABLE DECLARATION. a = highest number so far, b = position of that number
entireLoop:
for (var i = 1; i<=input.length; i++)
{
if(input[i] > input[i-1])
{
for(var o = i; o>=0; o--)
{
if(input[i-1] > input[o])
{
input.splice(i,0,input[o]);
input.splice((o+1),1);
continue entireLoop;
}
else if(input[o] > input[0])
{
input.splice(0,0,input[o]);
input.splice((o+1),1);
continue entireLoop;
}
}
}
}
document.write(input);
I’m trying to order the array from largest to smallest, but there’s a 32 stuck somewhere. I know there’s the sort method, but I’m a newbie and want to try this for myself.
** edit **
First have a look at the Array’s native .sort() method. It leaves the original array intact and accepts a comparison function. The latter makes .sort() pretty powerful.
So if we want to use bubbleSort ( link provided by T.J. Crowder , see OP comments ) we can write the following:
Lets walk through it step by step:
Our function accepts 2 parameters, first the array and 2nd an optional comparison function.
We store the list’s length under variable
i, and declare 2 empty variables (swappedandval) we’re going to use later on.We clone the list using
[].concat( array )and overwrite the locallistvariable leaving the original intact.We test the
typeofthecomparisonargument, if it’s afunctionwe use that one, otherwise we fall back on our owncomparisonfunction. Our fallback comparison function will returntrueifais bigger thanb.A do/while loop will run at least once, our
swappedvariable is currentlyundefinedso it will be interpreted as falsy. If ourcomparisonfunction returns true, a swap occurs and theswappedvariable will be set to true, so it will loop again.Here I loop from the list’s length downward, the
--operator is put before theivariable to ensure it is handled first before anything,i--would go off afterwhileevaluation causing erronous results sincelist[ list.length ]does not exist. I always do it this way (bad habbit perhaps), but if it confuses you, go for absolute transparancy.First we check if
ihas a truthy value ( 0 evaluates to falsy ) and then we run thecomparisonfunction passinglist[ i ]andlist[ i - 1 ]asaandbparameters. If thecomparisonfunction returnstrue, we perform a swap.Here I perform the swap without using the
.splice()method, it’s just an educated guess atm., but I figure direct assignments are faster then function calls. I use thevalvariable as a place holder. After the swap is done, I setswappedto true so our do/while loop will continue.Well… return the result.
I’ve excluded some checks, like what do we do when the list’s length is 0 and whatnot. Basically when writing helper functions, we also need to deal with error handling. Like for example throwing a TypeError when the passed comparison argument is not a function, ensuring the comparison method returns a boolean value and so on.