View Full Version : Newbie who needs help with array function

10-22-2006, 07:54 AM
How could I implement two sort functions w/o using the "sort" built-in-method: 1) the first will return a sorted array 2) the second will sort the array passed into it directly - the first function called f1 can be called by:

var a = [2, 4, 3, 1];
var b = f1(a, "d");

After execution, a shouldn't be changed and b should become an array containing [4,3,2,1]

Second function called f2 and be called using this code:

var a = [2, 4, 3, 1];
f2(a, "d");

After execution, a should contain [4, 3, 2, 1]

If anyone can help I would greatly appreciate it!!!

10-22-2006, 08:21 AM
Just use the built in sort method. it will be faster than anything you can write in javascript....

If you don't want the array to be changed, coppy it.

If you need a numeric sort, define your own sort function...

var myArr = [4, 1, 3, 2];

//Copy myArr so that it doesn't change.
var arr = new Array();

arr.sort(function(a,b){return a-b}); //ascending numeric sort
arr.sort(function(a,b){return b-a}); //descending numeric sort

The only reason you need to write your own sort routine without using the built in sort is if you're doing this for a class... If you're doing this for a class, then post the code you're having problems with and we'll help. We will not do the work for you.