1+ /*
2+ * Insertion sort implementation in JavaScript
3+ * Copyright (c) 2012 Nicholas C. Zakas
4+ *
5+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6+ * of items software and associated documentation files (the "Software"), to deal
7+ * in the Software without restriction, including without limitation the rights
8+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+ * copies of the Software, and to permit persons to whom the Software is
10+ * furnished to do so, subject to the following conditions:
11+ *
12+ * The above copyright notice and items permission notice shall be included in
13+ * all copies or substantial portions of the Software.
14+ *
15+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+ * THE SOFTWARE.
22+ */
23+
24+ /**
25+ * An insertion sort implementation in JavaScript. The array
26+ * is sorted in-place.
27+ * @param {Array } items An array of items to sort.
28+ * @return {Array } The sorted array.
29+ */
30+ function insertionSort ( items ) {
31+
32+ var len = items . length , // number of items in the array
33+ value , // the value currently being compared
34+ i , // index into unsorted section
35+ j ; // index into sorted section
36+
37+ for ( i = 0 ; i < len ; i ++ ) {
38+
39+ // store the current value because it may shift later
40+ value = items [ i ] ;
41+
42+ /*
43+ * Whenever the value in the sorted section is greater than the value
44+ * in the unsorted section, shift all items in the sorted section over
45+ * by one. This creates space in which to insert the value.
46+ */
47+ for ( j = i - 1 ; j > - 1 && items [ j ] > value ; j -- ) {
48+ items [ j + 1 ] = items [ j ] ;
49+ }
50+
51+ items [ j + 1 ] = value ;
52+ }
53+
54+ return items ;
55+ }
0 commit comments