I have a sorted javascript array, and want to insert one more item into the array such the resulting array remains sorted. I could certainly implement a simple quicksort-style insertion function:
var array = [1,2,3,4,5,6,7,8,9];
var element = 3.5;
function insert(element, array) {
array.splice(locationOf(element, array)+1, 0, element);
return array;
}
function locationOf(element, array, start, end) {
start = start || 0;
end = end || array.length-1;
var pivot = parseInt(start + (end - start) / 2);
if(end-start <= 1 || array[pivot] == element) return pivot;
if(array[pivot] < element) {
return locationOf(element, array, pivot, end);
} else{
return locationOf(element, array, start, pivot);
}
}
print(insert(element, array));
However, I noticed that implementations of the Array.sort function might potentially do this for me, and natively:
var array = [1,2,3,4,5,6,7,8,9];
var element = 3.5;
function insert(element, array) {
array.push(element);
array.sort(function(a,b) {return a-b});
return array;
}
print(insert(element, array));
Is there a good reason to choose the first implementation over the second?
Edit: Note that for the general case, an O(log(n)) insertion (as implemented in the first example) will be faster than a generic sorting algorithm; however this is not necessarily the case for javascript in particular. Note that:
- Best case for several insertion algorithms is O(n), which is still significantly different from O(log(n)), but not quite as bad as O(n log(n)) as mentioned below. It would come down to the particular sorting algorithm used (see http://stackoverflow.com/questions/234683/javascript-array-sort-implementation)
- The sort method in javascript is a native function, so potentially realizing huge benefits -- O(log(n)) with a huge coefficient can still be much worse than O(n) for reasonably sized data sets.