forked from thuva4/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (62 loc) · 1.49 KB
/
Copy pathindex.js
File metadata and controls
69 lines (62 loc) · 1.49 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const partialSort = (string, iteration) => {
const chars = string.split('');
if (chars.length <= 1) {
return string;
} else if (isSorted(chars)) {
return string;
}
return rerangeArray(chars, iteration).join('');
};
const rerangeArray = (array, k) => {
if (k === 0) {
return array;
}
const sortedArray = [];
let unSortedArray = array;
while (k > 0 && unSortedArray.length > 0) {
const {minIndex} = findMinimum(unSortedArray, k);
let processedArray = unSortedArray;
if (minIndex !== 0) {
processedArray = arrayMove(unSortedArray, minIndex, 0);
k -= minIndex;
}
const [min, ...restArray] = processedArray;
sortedArray.push(min);
unSortedArray = restArray;
}
return [...sortedArray, ...unSortedArray];
};
const arrayMove = (array, oldIndex, newIndex) => {
if (newIndex >= array.length) {
let count = newIndex - array.length + 1;
while (count--) {
array.push(undefined);
}
}
array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
return array;
};
const findMinimum = (array, iteration) => {
let min = array[0];
let minIndex = 0;
for (let i =1; i <= iteration; i++) {
if (min > array[i] && i <= iteration) {
min = array[i];
minIndex = i;
}
}
return {min, minIndex};
};
const isSorted = (arr) => {
let sorted = true;
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i+1]) {
sorted = false;
break;
}
}
return sorted;
};
module.exports = {
partialSort,
};