-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertion_sort.js
60 lines (46 loc) · 1.16 KB
/
insertion_sort.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
/**
* Insertion sort works like a card game, where you have to
* sort the cards in ascending order. When you pick up a new card
* you'll probably looks at your hand to see the current order.
* If the left card is bigger than the card in your hand, so you
* have to put you card at the same position that left card is.
* And the left card will increase (+1) your position.
*/
function ascending_insertion_sort(vector) {
var i;
var j;
var aux;
/* We start at index 1,
by induction our first index (0)
is already sorted... because we don't have
anything on the left side.
*/
for (i = 1; i < vector.length; i++) {
aux = vector[i];
j = i - 1;
while ( j >= 0 && aux < vector[j]) {
vector[j+1] = vector[j];
j--;
}
vector[j+1] = aux;
}
return vector;
}
function descending_insertion_sort(vector) {
var i;
var j;
var aux;
for (i = 1; i < vector.length; i++) {
aux = vector[i];
j = i - 1;
while ( j >= 0 && aux > vector[j]) {
vector[j+1] = vector[j];
j--;
}
vector[j+1] = aux;
}
return vector;
}
vector = [31, 41, 59, 26, 41, 58];
// ascending_insertion_sort(vector);
// descending_insertion_sort(vector);