Skip to content

Commit f8d2e37

Browse files
authored
Update insertionsort.js
1 parent c7f3fa5 commit f8d2e37

File tree

1 file changed

+13
-59
lines changed

1 file changed

+13
-59
lines changed

functions/insertionsort.js

Lines changed: 13 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,16 @@
1-
2-
// Insertion Sort
3-
function insertionSort(arr) {
4-
5-
let n = arr.length;
6-
7-
for (let i = 1; i < n; i++) {
8-
let key = arr[i];
9-
let j = i - 1;
10-
11-
while (j >= 0 && arr[j] > key) {
12-
arr[j + 1] = arr[j];
13-
j = j - 1;
1+
let insertionSort = {
2+
sort: (input, animation) => {
3+
for (let i=1; i<input.length; i++){
4+
let number = input[i]
5+
let indices = []
6+
for (let j = i-1; j >= 0; j--) {
7+
if (input[j] > number) {
8+
indices = [j, i]
9+
input[j+1] = input[j]
10+
input[j] = number
11+
}
12+
}
13+
if (indices.length) animation.push({indices: indices, sorted:false})
1414
}
15-
arr[j + 1] = key;
1615
}
17-
18-
return arr;
1916
}
20-
21-
22-
// Modified insertion sort to place each iteration and details within a JavaScript object
23-
function captureInsertionSort(arr) {
24-
25-
let n = arr.length;
26-
let iterArr = [];
27-
let numIterations = 0;
28-
let numSwaps = 0;
29-
let numComparisons = 0;
30-
31-
for (let i = 1; i < n; i++) {
32-
numIterations++;
33-
numComparisons = 0;
34-
numSwaps = 0;
35-
let key = arr[i];
36-
let j = i - 1;
37-
38-
numComparisons++;
39-
while (j >= 0 && arr[j] > key) {
40-
arr[j + 1] = arr[j];
41-
j = j - 1;
42-
numSwaps++;
43-
}
44-
arr[j + 1] = key;
45-
46-
if (numSwaps > 0) {
47-
numSwaps = 1;
48-
}
49-
50-
// Push copy of current array to iterations array object
51-
const iterArrObj = {};
52-
iterArrObj.iteration = numIterations;
53-
iterArrObj.comparisons = numComparisons;
54-
iterArrObj.swaps = numSwaps;
55-
iterArrObj.array = [...arr];
56-
iterArr.push(iterArrObj);
57-
}
58-
59-
return iterArr;
60-
}
61-
62-
export { insertionSort, captureInsertionSort };

0 commit comments

Comments
 (0)