-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsertion_sort.js
More file actions
executable file
·45 lines (34 loc) · 1.1 KB
/
insertion_sort.js
File metadata and controls
executable file
·45 lines (34 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env node --harmony
function insertionSort(unsorted) {
// empty array
var sorted = [];
// insert the first element
sorted.push(unsorted.shift());
// while there are elements in the unsorted array, pluck one
for(var unsorted_number; unsorted_number = unsorted.shift();) {
// then compare to values in our sorted array
for(var i=0, length = sorted.length; i <= length; i++) {
var sorted_number = sorted[i];
// compare to the sorted number, insert there,
// or at the end if this is the final run
if ((sorted_number > unsorted_number) || (length == i)) {
sorted.splice(i, 0, unsorted_number);
// we can exit this iteration now...
break
}
}
}
return sorted;
}
// read buffer
var rawInput = '';
process.stdin.resume();
process.stdin.on('data', function(chunk) {
rawInput += chunk.toString()
});
// nothing else to read, fire
process.stdin.on('end', function() {
// split and cast to Numbers
var input = rawInput.split(',').map(function(i){ return Number(i) });
process.stdout.write(insertionSort(input) + '\n');
});