-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselectionSort.js
executable file
·76 lines (63 loc) · 1.82 KB
/
selectionSort.js
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
** Recursive sorter.
Useage at the CLI:
node selectionSort.js 100 0 // sort 100 numbers in silent mode
node selectionSort.js 24 1 // sort 24 numbers in debugger mode
**
*/
/*
** Prints an array as a horizontal row.
** Accepts: an array. Accepts: how many items to display
** Returns part or all of the array. As a string.
*/
function showArrayH(showItems, stopRequest){
let len = showItems.length;
let stop = (showItems.length < stopRequest)? showItems.length - 1 : stopRequest - 1;
let i = 0, showString='';
while(i++ < stop){
showString += '| ' + String(showItems[i]);
}
return showString;
}
/*
** Just generate a test array.
** Accepts: number of ints to generate.
** Returns an array of numbers up to 999
**/
function makeArray(n) {
let allNums = [];
while(n--){
allNums.push(Math.round(Math.random() * 1000));
}
return allNums;
}
/*
** Sorting algorithm.
** Accepts an unsorted array.
** Returns a sorted array.
**/
function insertSort(raws){
for( let i = 0, stop = raws.length; i < stop; i++){
for( let j = i + 1; j < stop; j++){
// flag to run diagnostic mode, off by default
if (Boolean(process.argv[3]) > 0){console.log(`[${raws[i]}] and [${raws[j]}]`);}
if (raws[j] < raws[i]){
let c = raws[j];
raws[j] = raws[i];
raws[i] = c;
if (Boolean(process.argv[3]) > 0){console.log(`--------[${raws[i]}] and [${raws[j]}]`);}
}
} // end J
} // end I
return raws;
}
/*----M-A-I-N------------*/
console.log( `Started at ${( new Date()).toLocaleTimeString()}`);
let scores = makeArray(process.argv[2]);
console.log("\nUnsorted:");
console.log( showArrayH(scores, 14));
scores = insertSort(scores);
console.log("\nSorted:");
console.log( showArrayH(scores, 14));
console.log(`Run in test mode: ${Boolean( process.argv[3])} `);
console.log( `Finished at ${( new Date()).toLocaleTimeString()}`);