Skip to content

Commit 431f8be

Browse files
ms10398the-cybersapien
authored andcommitted
Add Selection Sort (#16)
1 parent 3736d0b commit 431f8be

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

CONTRIBUTORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
Aditya Aggarwal (the-cybersapien)
22
Jai Kathuria (jaikathuria)
3+
Mohit Sharma (ms10398)

Javascript/Sort/selection-sort.js

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

0 commit comments

Comments
 (0)