forked from blambodh/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-SearchingAlgorithms.js
executable file
·128 lines (101 loc) · 2.71 KB
/
01-SearchingAlgorithms.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
function ArrayList(){
var array = [];
this.insert = function(item){
array.push(item);
};
this.toString = function(){
var s = array[0] ? array[0] : '';
for (var i=1; i<array.length; i++){
s += ', ' + array[i];
}
return s;
};
this.sequentialSearch = function(item){
for (var i=0; i<array.length; i++){
if (item === array[i]){
return i;
}
}
return -1;
};
this.findMaxValue = function(){
var max = array[0];
for (var i=1; i<array.length; i++){
if (max < array[i]){
max = array[i];
}
}
return max;
};
this.findMinValue = function(){
var min = array[0];
for (var i=1; i<array.length; i++){
if (min > array[i]){
min = array[i];
}
}
return min;
};
this.binarySearch = function(item){
this.quickSort();
var low = 0,
high = array.length - 1,
mid, element;
while (low <= high){
mid = Math.floor((low + high) / 2);
element = array[mid];
console.log('mid element is ' + element);
if (element < item) {
low = mid + 1;
console.log('low is ' + low);
} else if (element > item) {
high = mid - 1;
console.log('high is ' + high);
} else {
console.log('found it');
return mid;
}
}
return -1;
};
this.quickSort = function(){
quick(array, 0, array.length - 1);
};
var partition = function(array, left, right) {
var pivot = array[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
swapQuickStort(array, i, j);
i++;
j--;
}
}
return i;
};
var swapQuickStort = function(array, index1, index2){
var aux = array[index1];
array[index1] = array[index2];
array[index2] = aux;
};
var quick = function(array, left, right){
var index;
if (array.length > 1) {
index = partition(array, left, right);
if (left < index - 1) {
quick(array, left, index - 1);
}
if (index < right) {
quick(array, index, right);
}
}
return array;
};
}