forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-SortingAlgorithms.js
79 lines (67 loc) · 1.76 KB
/
01-SortingAlgorithms.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
71
72
73
74
75
76
77
78
79
function ArrayList(){
var array = [];
this.insert = function(item){
array.push(item);
};
var swap = function(index1, index2){
var aux = array[index1];
array[index1] = array[index2];
array[index2] = aux;
};
this.toString= function(){
var s = array[0] ? array[0] : '';
for (var i=1; i<array.length; i++){
s += ', ' + array[i];
}
return s;
};
this.bubbleSort = function(){
var length = array.length;
for (var i=0; i<length; i++){
for (var j=0; j<length-1; j++ ){
if (array[j] > array[j+1]){
swap(j, j+1);
}
}
}
};
this.modifiedBubbleSort = function(){
var length = array.length,
swapped;
do {
swapped = false;
for (var i=0; i<length-1; i++){
if (array[i] > array[i+1]){
swap(i, i+1);
swapped = true;
}
}
} while (swapped);
};
this.selectionSort = function(){
var length = array.length,
indexMin;
for (var i=0; i<length; i++){
indexMin = i;
for (var j=i; j<length; j++){
if(array[indexMin]>array[j]){
indexMin = j;
}
}
swap(i, indexMin);
}
};
this.insertionSort = function(){
var length = array.length,
j, temp;
for (var i=1; i<length; i++){
j = i;
temp = array[i];
while (j>0 && array[j-1] > temp){
array[j] = array[j-1];
j--;
}
array[j] = temp;
}
};
}