1+ /*
2+ * Selection sort implementation in JavaScript
3+ * Copyright (c) 2009 Nicholas C. Zakas
4+ *
5+ * Permission is hereby granted, free of charge, to any person obtaining a copy
6+ * of this 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 this 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+ /**
26+ * Swaps two values in an array.
27+ * @param {Array } items The array containing the items.
28+ * @param {int } firstIndex Index of first item to swap.
29+ * @param {int } secondIndex Index of second item to swap.
30+ * @return {void }
31+ */
32+ function swap ( items , firstIndex , secondIndex ) {
33+ var temp = items [ firstIndex ] ;
34+ items [ firstIndex ] = items [ secondIndex ] ;
35+ items [ secondIndex ] = temp ;
36+ }
37+
38+ /**
39+ * A selection sort implementation in JavaScript. The array
40+ * is sorted in-place.
41+ * @param {Array } items An array of items to sort.
42+ * @return {Array } The sorted array.
43+ */
44+ function selectionSort ( items ) {
45+
46+ var len = items . length ,
47+ min ;
48+
49+ for ( i = 0 ; i < len ; i ++ ) {
50+
51+ //set minimum to this position
52+ min = i ;
53+
54+ //check the rest of the array to see if anything is smaller
55+ for ( j = i + 1 ; j < len ; j ++ ) {
56+ if ( items [ j ] < items [ min ] ) {
57+ min = j ;
58+ }
59+ }
60+
61+ //if the minimum isn't in the position, swap it
62+ if ( i != min ) {
63+ swap ( items , i , min ) ;
64+ }
65+ }
66+
67+ return items ;
68+ }
0 commit comments