-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgos.js
More file actions
100 lines (83 loc) · 2.77 KB
/
algos.js
File metadata and controls
100 lines (83 loc) · 2.77 KB
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
const LinearSearch = (list, value) => {
/**
* Searches for element in array. Complexity O(n)
* @param {array} list Array of numbers
* @param {Number} value Searched number
* @return {Number} Returns element's index ( first found in array )
*/
// goes thought all elements in list until finds needed element
for (let i = 0; i < list.length; i++) {
if (list[i] === value) {
return i;
}
}
// return -1 if element not found or array is empty
return -1;
};
let array = [4, 8, 7, 2, 11, 1, 3];
console.log(LinearSearch(array, 3));
const mergeSort = (list) => {
/**
* Sorts array. Complexity O(n log(n))
* @param {array} list Array of numbers
* @return {array} Returns sorted array of numbers
*/
// if length of array is 2 or less step out of recursion
if (list.length <= 2) {
// if list[0] > list[1] swap numbers to sort them
if (list.length === 2) {
if (list[0] > list[1]) {
const temp = list[0];
list[0] = list[1];
list[1] = temp
}
}
console.log(list);
return list;
}
// recursively dividing array in half's
let mid = Math.floor(list.length / 2);
let left = mergeSort(list.slice(0, mid));
let right = mergeSort(list.slice(mid));
let sorted = [];
// while one of the arrays is not empty take smaller number from one of the arrays,
// add number to end of sorted array and remove it from previous
while (left.length !== 0 && right.length !== 0) {
// compare first elements of arrays
if (right[0] < left[0]) {
sorted.push(right.shift());
} else {
sorted.push(left.shift());
}
}
// concatenate sorted array with not empty array
if (left.length !== 0) {
return sorted.concat(left)
} else {
return sorted.concat(right)
}
};
let array = [4, 8, 7, 2, 11, 1, 3];
console.log(mergeSort(array));
const Bubble = (list) => {
/**
* Sorts array. Complexity O(n^2)
* @param {array} list Array of numbers
* @return {array} Returns sorted array of numbers
*/
// goes through array of numbers
for (let i = 0; i < list.length; i++) {
// check pairs of numbers till list.length - i and swap if bigger number is list[j] > list[j + 1]
for (let j = 0; j < list.length - i - 1; j++) {
if (list[j] > list[j + 1]) {
// swap
const temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
return list;
};
let array = [4, 8, 7, 2, 11, 1, 3];
console.log(Bubble(array));