-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssort.js
72 lines (59 loc) · 1.76 KB
/
ssort.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
import {swap, signedCompare as SC} from './quicksort.js';
const DEFAULT_OPTS = {
compare: undefined, /* uses DEFAULT_COMPARE, but can be a custom comparison */
inplace: true, /* sort is in place,
/* false is create a new array without changing original */
nosplice: true, /* don't use array splice operations on inplace array instead use swaps */
}
export default function SelectionSort(data, opts) {
if ( ! opts ) {
opts = DEFAULT_OPTS;
}
opts = Object.assign({}, DEFAULT_OPTS, opts);
opts = Object.freeze(opts);
if ( opts.inplace ) {
if ( opts.nosplice ) {
for( let start = 0; start < data.length; start++ ) {
const minIndex = findMin(data, start, opts);
let j = minIndex;
while(j > start) {
swap(data, j, j-1);
j--;
}
}
} else {
for( let start = 0; start < data.length; start++ ) {
const minIndex = findMin(data, start, opts);
const minVal = data[minIndex];
data.splice(minIndex, 1);
data.splice(start, 0, minVal);
}
}
return data;
} else {
const sortedList = [];
while(data.length) {
const minIndex = findMin(data, 0, opts);
const minVal = data.splice(minIndex,1)[0];
sortedList.push(minVal);
}
return sortedList;
}
}
export const sort = SelectionSort;
export const signedCompare = SC;
function findMin(arr, start, opts) {
let minValue = arr[start];
let minIndex = start;
for( let i = start; i < arr.length; i++ ) {
const val = arr[i];
const comparison = signedCompare(minValue, val, opts);
if ( comparison >= 0 ) {
// do nothing
} else {
minValue = val;
minIndex = i;
}
}
return minIndex;
}