Insertion Sort.
Best: O(n), Average: O(n2), Worst: O(n2)
Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is built one entry at a time.
Visit Wikipedia for more information.
//Programmer: Larry Battle Mar 9, 2011
//Purpose: Insertion sort implemented in Javascript.
var insertionSort = function (arr) {
var len = arr.length, i = -1, j, tmp;
while (len--) {
tmp = arr[++i];
j = i;
while (j-- && arr[j] > tmp) {
arr[j + 1] = arr[j];
}
arr[j + 1] = tmp;
}
};
insertionSort( [5,4,3,2,1] ); //returns [1,2,3,4,5];
insertionSort( [ "bear", "dog", "cat" ] ) // returns ["bear", "cat", "dog"];
Here’s a great short video tutorial to help those clueless about insertion sort.
Update:
/**
* Sorts an array using insertion sort.
*
* @param {Array} - arr
* @param {Boolean} areNumbers indicates whether the array elements should be cast as numbers.
* @return {Array} the sorted array.
*/
var insertionSort = function (arr, areNumbers) {
arr = arr.concat();
var len = arr.length,
i = -1,
j,
tmp;
while (len--) {
tmp = arr[++i];
j = i;
while (j-- && areNumbers ? (+arr[j] > +tmp) : (arr[j] > tmp) ) {
arr[j + 1] = arr[j];
}
arr[j + 1] = tmp;
}
return arr;
};
// Treat input as array of numbers
Input: insertionSort(["1","2","3","4","4","40","20","21"], true);
Output: ["1", "2", "3", "4", "4", "20", "21", "40"]
// Treat input as array of strings
Input: insertionSort(["1","2","3","4","4","40","20","21"]);
Output: ["1", "2", "20", "21", "3", "4", "4", "40"]
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…
View Comments
Demo:
Demo of alternative sort speed up
Yeah... no. Apparently you're still one of those clueless about insertion sort. Try adding the number 11 to your demo and see where it ends up, champ.
Oh. But that is a slight bug. However, the algorithm is still correct but the way I supplied the input isn't.
The problem in my demo is that I forgot to convert the input from an array of strings to an array of numbers. Oh well.
Thanks for your feedback.
Looks good.. Thanks..