-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew_insertion_sort.js
More file actions
47 lines (43 loc) · 877 Bytes
/
Copy pathnew_insertion_sort.js
File metadata and controls
47 lines (43 loc) · 877 Bytes
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
/*The worst case scenario is not the only situation worth considering*/
let array3 = [9, 8, 7, 6, 5, 4, 3, 2, 1];
function myInsertionSort(list)
{
for(let i = 1; i < list.length; i++)
{
let temp_value = list[i];
let mainGapIndex = i;
for(let j = i - 1; j >= 0; j--)
{
if(list[j] > temp_value)
{
list[mainGapIndex] = list[j];
mainGapIndex = j;
}
else
break;
}
list[mainGapIndex] = temp_value;
}
return list;
}
function insertionSort_book(list)
{
for(let i = 1; i < list.length; i++)
{
let temp_value = list[i];
let position = i - 1;
while(position >= 0)
{
if(list[position] > temp_value)
{
list[position + 1] = list[position];
position = position - 1;
}
else
break;
}
list[position + 1] = temp_value;
}
return list;
}
console.log(myInsertionSort(array3));