Skip to content

Commit aa5f07c

Browse files
Merge pull request #6 from ms10398/master
Added Implementation of Selection Sort
2 parents 1928b15 + e846f8f commit aa5f07c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Sorts/selectionSort.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*The selection sort algorithm sorts an array by repeatedly finding the minimum element
2+
*(considering ascending order) from unsorted part and putting it at the beginning. The
3+
*algorithm maintains two subarrays in a given array.
4+
*1) The subarray which is already sorted.
5+
*2) Remaining subarray which is unsorted.
6+
*
7+
*In every iteration of selection sort, the minimum element (considering ascending order)
8+
*from the unsorted subarray is picked and moved to the sorted subarray.
9+
*/
10+
function selectionSort(items) {
11+
var length = items.length;
12+
for (var i = 0; i < length - 1; i++) {
13+
//Number of passes
14+
var min = i; //min holds the current minimum number position for each pass; i holds the Initial min number
15+
for (var j = i + 1; j < length; j++) { //Note that j = i + 1 as we only need to go through unsorted array
16+
if (items[j] < items[min]) { //Compare the numbers
17+
min = j; //Change the current min number position if a smaller num is found
18+
}
19+
}
20+
if (min != i) {
21+
//After each pass, if the current min num != initial min num, exchange the position.
22+
//Swap the numbers
23+
var tmp = items[i];
24+
items[i] = items[min];
25+
items[min] = tmp;
26+
}
27+
}
28+
}
29+
30+
//Implementation of Selection Sort
31+
32+
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
33+
//Array before Sort
34+
console.log(ar);
35+
selectionSort(ar);
36+
//Array after sort
37+
console.log(ar);

0 commit comments

Comments
 (0)