SlideShare uma empresa Scribd logo
1 de 288
So why do you need to
know Algorithms and
Data Structures in
Front-end, anyway
Adam Leos
Adam Leos
● Старший разработчик
PlutoTV
Adam Leos
● Старший разработчик
PlutoTV
● Автор веб-дополнения
UnlimitedControl
https://adam4leos.github.io/
Статья на
Хабре:
● Русский
● English
Adam Leos
● Старший разработчик
PlutoTV
● Автор веб-дополнения
UnlimitedControl
● Докладчик-идеолог
Что вы видите,
это не то, что
исполняется ©
Что вы видите,
это не то, что
исполняется ©
Нет плохого
кода, а есть
плохие
компиляторы ©
Сложность алгоритма
Сложность алгоритма
Big O notation, O
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n)
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n)
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
logarithmic
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
logarithmic polynomial
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
logarithmic polynomial
Ο(f(n)) = { g(n) : there exists c > 0 and n0
such that f(n) ≤ c.g(n)
for all n > n0
. }
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
logarithmic polynomial
Ο(f(n)) = { g(n) : there exists c > 0 and n0
such that f(n) ≤ c.g(n)
for all n > n0
. }
c and
n0
are constants, f(n)
and
g(n) are functions over
non-negative integers
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
logarithmic polynomial
Ο(f(n)) = { g(n) : there exists c > 0 and n0
such that f(n) ≤ c.g(n)
for all n > n0
. }
c and
n0
are constants, f(n)
and
g(n) are functions over
non-negative integers
Сложность алгоритма
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
logarithmic polynomial
Ο(f(n)) = { g(n) : there exists c > 0 and n0
such that f(n) ≤ c.g(n)
for all n > n0
. }
c and
n0
are constants, f(n)
and
g(n) are functions over
non-negative integers
Algorithm Complexity
Big O notation, O
Omega notation, Ω
Theta Notation, θ
asymptotic notations, asymptotic complexity
O(n) Ο(log n) O(n * logn)
logarithmic polynomial
Ο(f(n)) = { g(n) : there exists c > 0 and n0
such that f(n) ≤ c.g(n)
for all n > n0
. }
c and
n0
are constants, f(n)
and
g(n) are functions over
non-negative integers
Сложность алгоритма
Сложность алгоритма
Как будет расти расход ресурсов* с
увеличением размера входных данных.
Сложность алгоритма
Как будет расти расход ресурсов* с
увеличением размера входных данных.
* время и память
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
sumNumbersInArray([1, 2, 3, 4, 5]);
Сложность алгоритма
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
sumNumbersInArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
Сложность алгоритма
Как будет расти расход ресурсов* с
увеличением размера входных данных.
* время и память
Big O notation, O
Big O notation, O
Big O notation, O
Функция, которая описывает рост сложности
алгоритма.
Big O notation, O
function sumNumbersInArray(array) {
let sum = 0;
array.forEach(number => sum += number);
return sum;
}
Размер входных данных, ед.
Размер входных данных, ед.
1
Размер входных данных, ед.
1 100
Размер входных данных, ед.
1 100 1000
Размер входных данных, ед.
1 100 1000 10000
Размер входных данных, ед.
1 100 1000 10000
Размер входных данных, ед.
1 100 1000 10000
Количествоопераций
Размер входных данных, ед.
1 100 1000 10000
Количествоопераций
1
100
1000
10000
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
Количествоопераций
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
O(n)
Количествоопераций
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
O(n) - линейная
Количествоопераций
Big O
function simpleCalculate() {
const a = 1 + 2;
const b = 3 + 4;
console.log('calculating...');
return b - a;
}
simpleCalculate();
Big O
function simpleCalculate() {
const a = 1 + 2;
const b = 3 + 4;
console.log('calculating...');
return b - a;
}
simpleCalculate();
O(1)
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
O(1)
Количествоопераций
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
O(1) - константная (постоянная)
Количествоопераций
Big O
function simpleCalculate(number) {
const a = 1 + 2;
const b = 3 + 4;
console.log('calculating...');
return b - a + number;
}
simpleCalculate(8);
Big O
function simpleCalculate(number) {
const a = 1 + 2;
const b = 3 + 4;
console.log('calculating...');
return b - a + number;
}
simpleCalculate(8);
O(1)
Big O
function simpleCalculate(array) {
const a = 1 + 2;
const b = 3 + 4;
let additionalNumber = 0;
array.forEach(num => additionalNumber += num);
return b - a + additionalNumber;
}
simpleCalculate([1, 2, 5, 10, 1223]);
Big O
function simpleCalculate(array) {
const a = 1 + 2;
const b = 3 + 4;
let additionalNumber = 0;
array.forEach(num => additionalNumber += num);
return b - a + additionalNumber;
}
simpleCalculate([1, 2, 5, 10, 1223]);
O(n)
Big O
function simpleCalculate(array) {
const a = 1 + 2;
const b = 3 + 4;
const additionalNumber = array.length;
return b - a + additionalNumber;
}
simpleCalculate([1, 2, 5, 10, 1223]);
Big O
function simpleCalculate(array) {
const a = 1 + 2;
const b = 3 + 4;
const additionalNumber = array.length;
return b - a + additionalNumber;
}
simpleCalculate([1, 2, 5, 10, 1223]);
O(1)
Big O
function notSoSimpleCalculate(array) {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
array[i] = array[i] + array[j];
}
}
return array;
}
notSoSimpleCalculate([1, 2, 3]);
Big O
function notSoSimpleCalculate(array) {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
array[i] = array[i] + array[j];
}
}
return array;
}
notSoSimpleCalculate([1, 2, 3]);
O(n^2)
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
O(n^2) - квадратичная
Количествоопераций
Big O
function notSoSimpleCalculate(array) {
array.forEach(num => console.log(num));
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
array[i] = array[i] + array[j];
}
}
return array;
}
Big O
function notSoSimpleCalculate(array) {
array.forEach(num => console.log(num));
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
array[i] = array[i] + array[j];
}
}
return array;
}
O(n^2)
Big O
function mightBeSimpleCalculate(array) {
let total = 0;
array.forEach(num => {
const additional = array.indexOf(num) > 5 ? 5 : 1;
total = total + num + additional;
});
return array;
}
Big O
function mightBeSimpleCalculate(array) {
let total = 0;
array.forEach(num => {
const additional = array.indexOf(num) > 5 ? 5 : 1;
total = total + num + additional;
});
return array;
}
O(n^2)
Big O
function mightBeSimpleCalculate(array) {
let total = 0;
array.forEach(num => {
const additional = array.indexOf(num) > 5 ? 5 : 1;
total = total + num + additional;
});
return array;
}
O(n^2)
Big O
function mightBeSimpleCalculate(array) {
let total = 0;
array.forEach((num, index) => {
const additional = index > 5 ? 5 : 1;
total = total + num + additional;
});
return array;
}
O(n)
Пример роста в цифрах
Пример роста в цифрах
Входные данные - 10000 элементов
Пример роста в цифрах
O(1) - 1
Входные данные - 10000 элементов
Пример роста в цифрах
O(1) - 1
O(n) - 10000
Входные данные - 10000 элементов
Пример роста в цифрах
O(1) - 1
O(n) - 10000
O(n^2) - 100000000 (сто миллионов)
Входные данные - 10000 элементов
Пример роста в цифрах
O(1) - 1
O(n) - 10000
O(n^2) - 100000000 (сто миллионов)
O(n^3) - 1000000000000 (один триллион)
Входные данные - 10000 элементов
Пример роста в цифрах
O(1) - 1
O(n) - 10000
O(n^2) - 100000000 (сто миллионов)
O(n^3) - 1000000000000 (один триллион)
O(n!) очень много
100000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000……
Входные данные - 10000 элементов
Структуры данных
Структуры данных
Определенный способ организации
данных для максимально эффективного
использования
Структуры данных
● Доступ (получить данные)
● Поиск (найти данные)
● Вставка (добавить данные)
● Удаление (удалить данные)
Структуры данных
1. Массивы
Массивы
const arr = [1, 2, 3];
Массивы
const arr = [1, 2, 3];
arr[1]; // 2
Массивы
const arr = [1, 2, 3];
arr[1]; // 2 O(1)
Массивы
const arr = [1, 2, 3];
arr[1]; // 2
arr[2]; // 3
O(1)
O(1)
Массивы
const arr = [1, 2, 3];
arr[1]; // 2
arr[2]; // 3
arr[9]; // undefined
O(1)
O(1)
O(1)
Массивы
const arr = [1, 2, 3];
arr[1]; // 2
arr[2]; // 3
arr[9]; // undefined
arr[0] = 4; // [4, 2, 3]
O(1)
O(1)
O(1)
O(1)
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4] O(1)*
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
O(1)*
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3] O(1)
O(1)*
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
arr.shift(); // [2, 3]
O(1)
O(1)*
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
arr.shift(); // [2, 3]
O(1)
O(n)
O(1)*
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
arr.shift(); // [2, 3]
arr.unshift(4); // [4, 2, 3]
O(1)
O(n)
O(1)*
Массивы
const arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
arr.shift(); // [2, 3]
arr.unshift(4); // [4, 2, 3]
O(1)
O(n)
O(n)
O(1)*
Массивы O(n)
Массивы
.map()
.slice()
.every()
.filter()
.indexOf()
.reduce()
.reverse()
.find()
.includes()
.toString()
O(n)
Структуры данных
1. Массивы
2. Объекты
Объекты
const obj = {
id: 1,
name: 'Adam',
};
Объекты
const obj = {
id: 1,
name: 'Adam',
};
obj.id // 1
Объекты
const obj = {
id: 1,
name: 'Adam',
};
obj.id // 1 O(1)
Объекты
const obj = {
id: 1,
name: 'Adam',
};
obj.id // 1
obj['name'] // 1
O(1)
O(1)
Объекты
const obj = {
id: 1,
name: 'Adam',
};
obj.surname = 'Leos';
obj['name'] = [];
O(1)
O(1)
Объекты
const obj = {
id: 1,
name: 'Adam',
};
Object.keys(obj) // ['id', 'name']
Object.values(obj) // [1, 'Adam']
Объекты
const obj = {
id: 1,
name: 'Adam',
};
Object.keys(obj) // ['id', 'name']
Object.values(obj) // [1, 'Adam']
O(n)
O(n)
Объекты Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
function countSymbols(string) {
const dict = {};
for (let i = 0; i < string.length; i++) {
const iterableSymbol = string[i];
if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0;
dict[iterableSymbol]++;
}
return dict;
}
Посчитать символы в строке
Объекты
countSymbols('adam') // Object { a: 2, d: 1, m: 1 }
countSymbols('mississippi') // Object { m: 1, i: 4, s: 4, p: 2 }
Посчитать символы в строке
Полезный мапинг в
реальном мире
const shows = [
{
id: 1,
name: 'Rick and Morty',
categories: [
'Comedy',
'Animated',
'Science',
],
data: 1001010101001011,
},
{/.../},
{/.../},
{/.../},
{/.../},
];
const shows = [
{
id: 1,
name: 'Rick and Morty',
categories: [
'Comedy',
'Animated',
'Science',
],
data: 1001010101001011,
},
{/.../},
{/.../},
{/.../},
{/.../},
];
const bannedShows = [
{
id: 1,
name: 'Rick and Morty',
categories: [
'Comedy',
'Animated',
'Science',
],
},
{/.../},
];
function ineffectiveBanning(shows) {
shows.forEach(show => {
const { id: showID } = show;
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
if (showID === bannedShowID) {
show.isBanned = true;
};
});
});
};
function ineffectiveBanning(shows) {
shows.forEach(show => {
const { id: showID } = show;
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
if (showID === bannedShowID) {
show.isBanned = true;
};
});
});
};
function ineffectiveBanning(shows) {
shows.forEach(show => {
const { id: showID } = show;
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
if (showID === bannedShowID) {
show.isBanned = true;
};
});
});
};
function ineffectiveBanning(shows) {
shows.forEach(show => {
const { id: showID } = show;
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
if (showID === bannedShowID) {
show.isBanned = true;
};
});
});
};
function ineffectiveBanning(shows) {
shows.forEach(show => {
const { id: showID } = show;
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
if (showID === bannedShowID) {
show.isBanned = true;
};
});
});
};
function ineffectiveBanning(shows) {
shows.forEach(show => {
const { id: showID } = show;
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
if (showID === bannedShowID) {
show.isBanned = true;
};
});
});
};
function ineffectiveBanning(shows) {
shows.forEach(show => {
const { id: showID } = show;
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
if (showID === bannedShowID) {
show.isBanned = true;
};
});
});
};
function effectiveBanning(shows) {
const bannedShowsIDMap = {};
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
bannedShowsIDMap[bannedShowID] = true;
};
shows.forEach(show => {
const { id: showID } = show;
if (bannedShowsIDMap[showID]) show.isBanned = true;
});
};
function effectiveBanning(shows) {
const bannedShowsIDMap = {};
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
bannedShowsIDMap[bannedShowID] = true;
};
shows.forEach(show => {
const { id: showID } = show;
if (bannedShowsIDMap[showID]) show.isBanned = true;
});
};
function effectiveBanning(shows) {
const bannedShowsIDMap = {};
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
bannedShowsIDMap[bannedShowID] = true;
};
shows.forEach(show => {
const { id: showID } = show;
if (bannedShowsIDMap[showID]) show.isBanned = true;
});
};
function effectiveBanning(shows) {
const bannedShowsIDMap = {};
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
bannedShowsIDMap[bannedShowID] = true;
};
shows.forEach(show => {
const { id: showID } = show;
if (bannedShowsIDMap[showID]) show.isBanned = true;
});
};
function effectiveBanning(shows) {
const bannedShowsIDMap = {};
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
bannedShowsIDMap[bannedShowID] = true;
};
shows.forEach(show => {
const { id: showID } = show;
if (bannedShowsIDMap[showID]) show.isBanned = true;
});
};
function effectiveBanning(shows) {
const bannedShowsIDMap = {};
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
bannedShowsIDMap[bannedShowID] = true;
};
shows.forEach(show => {
const { id: showID } = show;
if (bannedShowsIDMap[showID]) show.isBanned = true;
});
};
function effectiveBanning(shows) {
const bannedShowsIDMap = {};
bannedShows.forEach(bannedShow => {
const { id: bannedShowID } = bannedShow;
bannedShowsIDMap[bannedShowID] = true;
};
shows.forEach(show => {
const { id: showID } = show;
if (bannedShowsIDMap[showID]) show.isBanned = true;
});
};
x100
Память в реальном мире
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels
.filter(filterEmptyTimelines)
.map(addIdentificator)
.map(modifyImages)
.map(removeParams)
.map(setSession)
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels.reduce((acc, channel) => {
if (hasEmptyTimelines(channel.timelines)) {
return acc;
}
const enchancedChannel =
setChannelURL(reduceImagesObject(addIDToChannel(channel)));
acc.push(enchancedChannel);
return acc;
}, []);
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels.reduce((acc, channel) => {
if (hasEmptyTimelines(channel.timelines)) {
return acc;
}
const enchancedChannel =
setChannelURL(reduceImagesObject(addIDToChannel(channel)));
acc.push(enchancedChannel);
return acc;
}, []);
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels.reduce((acc, channel) => {
if (hasEmptyTimelines(channel.timelines)) {
return acc;
}
const enchancedChannel =
setChannelURL(reduceImagesObject(addIDToChannel(channel)));
acc.push(enchancedChannel);
return acc;
}, []);
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels.reduce((acc, channel) => {
if (hasEmptyTimelines(channel.timelines)) {
return acc;
}
const enchancedChannel =
setChannelURL(reduceImagesObject(addIDToChannel(channel)));
acc.push(enchancedChannel);
return acc;
}, []);
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels.reduce((acc, channel) => {
if (hasEmptyTimelines(channel.timelines)) {
return acc;
}
const enchancedChannel =
setChannelURL(reduceImagesObject(addIDToChannel(channel)));
acc.push(enchancedChannel);
return acc;
}, []);
// more code
}
function enchanceApiResponse(apiResponse) {
const channels = apiResponse.channels.reduce((acc, channel) => {
if (hasEmptyTimelines(channel.timelines)) {
return acc;
}
const enchancedChannel =
setChannelURL(reduceImagesObject(addIDToChannel(channel)));
acc.push(enchancedChannel);
return acc;
}, []);
// more code
}
10-30%
Структуры данных
1. Массивы
2. Объекты
3. Графы
Граф
Граф
Вершина (узел)
Граф
Вершина (узел)
Ребро
Граф
Вершина (узел)
Ребро
1
13
9
54
11
6
70
Граф
1
13
9
54
11
6
70
Граф
1
13
9
54
11
6
70
Value (data) = 6
Граф
1
13
9
54
11
6
70
Value (data) = 6
Connections = [13, 70]
node = {
value: 6,
connections: [13, 70],
}
node = {
value: 6,
connections: [13, 70],
}
class Node {
}
node = {
value: 6,
connections: [13, 70],
}
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
}
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
addConnection(node) {
this.connections.push(node);
}
}
node = {
value: 6,
connections: [13, 70],
}
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
addConnection(node) {
this.connections.push(node);
}
}
node = {
value: 6,
connections: [13, 70],
}
const six = new Node(6);
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
addConnection(node) {
this.connections.push(node);
}
}
node = {
value: 6,
connections: [13, 70],
}
const six = new Node(6);
six.value; // 6
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
addConnection(node) {
this.connections.push(node);
}
}
node = {
value: 6,
connections: [13, 70],
}
const six = new Node(6);
six.value; // 6
const thirteen = new Node(13);
const seventy = new Node(70);
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
addConnection(node) {
this.connections.push(node);
}
}
node = {
value: 6,
connections: [13, 70],
}
const six = new Node(6);
six.value; // 6
const thirteen = new Node(13);
const seventy = new Node(70);
six.addConnection(thirteen);
six.addConnection(seventy);
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
addConnection(node) {
this.connections.push(node);
}
}
node = {
value: 6,
connections: [13, 70],
}
const six = new Node(6);
six.value; // 6
const thirteen = new Node(13);
const seventy = new Node(70);
six.addConnection(thirteen);
six.addConnection(seventy);
six.connections;
// [{ value: 13, connections: [] }, { value: 70, connections: [] }];
class Graph {
}
class Graph {
constructor() {
this.nodes = [];
}
}
class Graph {
constructor() {
this.nodes = [];
}
addNode(node) {
this.nodes.push(node);
}
}
class Graph {
constructor() {
this.nodes = [];
}
addNode(node) {
this.nodes.push(node);
}
addEdge(node1, node2) {
node1.addConnection(node2);
node2.addConnection(node1);
};
}
Граф
1
13
9
54
11
6
70
class Graph {
constructor() {
this.nodes = {};
}
addNode(node) {
this.nodes.push(node);
}
addEdge(node1, node2) {
node1.addConnection(node2);
node2.addConnection(node1);
};
}
const ourGraph = new Graph();
const one = new Node(1);
const six = new Node(6);
const nine = new Node(9);
const eleven = new Node(11);
const thirteen = new Node(13);
const fiftyFour = new Node(54);
const seventy = new Node(70);
class Graph {
constructor() {
this.nodes = {};
}
addNode(node) {
this.nodes.push(node);
}
addEdge(node1, node2) {
node1.addConnection(node2);
node2.addConnection(node1);
};
}
ourGraph.addNode(one);
ourGraph.addNode(six);
ourGraph.addNode(nine);
ourGraph.addNode(eleven);
ourGraph.addNode(thirteen);
ourGraph.addNode(fiftyFour);
ourGraph.addNode(seventy);
ourGraph.addEdge(one, thirteen);
ourGraph.addEdge(nine, thirteen);
ourGraph.addEdge(nine, fiftyFour);
ourGraph.addEdge(thirteen, eleven);
ourGraph.addEdge(thirteen, six);
ourGraph.addEdge(six, seventy);
Граф Гугл-карт
Kharkiv - [Lviv];
Lviv - [Kharkiv, Odessa];
Odessa - [Lviv];
Граф Гугл-карт
Kharkiv - [Lviv];
Lviv - [Kharkiv, Odessa];
Odessa - [Lviv];
Seattle
San Francisco
Las Vegas
Salt Lake City
San Francisco
Граф Гугл-карт
Kharkiv - [Lviv];
Lviv - [Kharkiv, Odessa];
Odessa - [Lviv];
const googleRoute = new Graph();
const googleRoute = new Graph();
const seattle = new Node('Seattle');
const sanFrancisco = new Node('San Francisco');
const lasVegas = new Node('Las Vegas');
const saltLakeCity = new Node('Salt Lake City');
const googleRoute = new Graph();
const seattle = new Node('Seattle');
const sanFrancisco = new Node('San Francisco');
const lasVegas = new Node('Las Vegas');
const saltLakeCity = new Node('Salt Lake City');
const seattleData = {
name: 'Seattle',
coordinates: [
47.7471188,
-125.6412592,
],
state: 'WA',
country: 'USA',
weather: 'Sunny',
/.../
};
const googleRoute = new Graph();
const seattle = new Node('Seattle');
const sanFrancisco = new Node('San Francisco');
const lasVegas = new Node('Las Vegas');
const saltLakeCity = new Node('Salt Lake City');
googleRoute.addNode(seattle);
googleRoute.addNode(sanFrancisco);
googleRoute.addNode(lasVegas);
googleRoute.addNode(saltLakeCity);
const googleRoute = new Graph();
const seattle = new Node('Seattle');
const sanFrancisco = new Node('San Francisco');
const lasVegas = new Node('Las Vegas');
const saltLakeCity = new Node('Salt Lake City');
googleRoute.addNode(seattle);
googleRoute.addNode(sanFrancisco);
googleRoute.addNode(lasVegas);
googleRoute.addNode(saltLakeCity);
googleRoute.addEdge(seattle, sanFrancisco);
googleRoute.addEdge(sanFrancisco, lasVegas);
googleRoute.addEdge(lasVegas, saltLakeCity);
googleRoute.addEdge(saltLakeCity, sanFrancisco);
const googleRoute = new Graph();
const seattle = new Node('Seattle');
const sanFrancisco = new Node('San Francisco');
const lasVegas = new Node('Las Vegas');
const saltLakeCity = new Node('Salt Lake City');
googleRoute.addNode(seattle);
googleRoute.addNode(sanFrancisco);
googleRoute.addNode(lasVegas);
googleRoute.addNode(saltLakeCity);
googleRoute.addEdge(seattle, sanFrancisco);
googleRoute.addEdge(sanFrancisco, lasVegas);
googleRoute.addEdge(lasVegas, saltLakeCity);
googleRoute.addEdge(saltLakeCity, sanFrancisco);
sanFrancisco.connections = [
seattle,
lasVegas,
saltLakeCity,
];
const googleRoute = new Graph();
const seattle = new Node('Seattle');
const sanFrancisco = new Node('San Francisco');
const lasVegas = new Node('Las Vegas');
const saltLakeCity = new Node('Salt Lake City');
googleRoute.addNode(seattle);
googleRoute.addNode(sanFrancisco);
googleRoute.addNode(lasVegas);
googleRoute.addNode(saltLakeCity);
googleRoute.addEdge(seattle, sanFrancisco);
googleRoute.addEdge(sanFrancisco, lasVegas);
googleRoute.addEdge(lasVegas, saltLakeCity);
googleRoute.addEdge(saltLakeCity, sanFrancisco);
sanFrancisco.connections = [
seattle,
lasVegas,
saltLakeCity,
];
seattle.connections = [
sanFrancisco
];
Логистика
1
13
9
54
11
6
70
Граф
Граф - ориентированный
1
13
9
54
11
6
70
1
13
9
54
11
6
70
4
2
7
20
8
1
Граф - взешенный
Где еще используются графы
1. Сеть (маршрутизация данных).
2. Логистика (маршруты, направления).
3. Телекоммуникации (планирование частот
вышек).
4. Социальные сети (возможные знакомые).
5. Рекомендации.
6. Схемы.
7. И еще очень много где.
Структуры данных
1. Массивы
2. Объекты
3. Графы
4. Деревья
1
13
9 54 11
6
70
Деревья
1
13
9 54 11
6
70
Деревья
=
Связный
ацикличный
граф
1
13
9 54 11
6
70
Деревья
=
Связный
ацикличный
граф
1
13
9 54 11
6
70
Деревья
=
Связный
ацикличный
граф
DOM дерево
const settings = {
};
const settings = {
options: [
],
};
const settings = {
options: [
{
},
{
},
{
},
// ...
],
};
const settings = {
options: [
{
name: 'video',
options: [...],
},
{
name: 'sound',
options: [...],
},
{
name: 'security',
options: [...],
},
// ...
],
};
const settings = {
options: [
{
name: 'video',
options: [...],
},
{
name: 'sound',
options: [...],
},
{
name: 'security',
options: [...],
},
// ...
],
};
[
{
name: 'subtitles',
options: [...],
},
{
name: 'brightness',
options: [...],
},
// ...
];
Алгоритмы
Алгоритмы
1. Поиск
function find(number, array) {
array.forEach((iterableNumber, index) => {
if (iterableNumber === number) {
console.log(`Found at index ${index}`);
}
});
}
function find(number, array) {
array.forEach((iterableNumber, index) => {
if (iterableNumber === number) {
console.log(`Found at index ${index}`);
}
});
}
O(n)
Поиск. Бинарный vs Последовательный
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
function binarySearch(number, array) {
let startIndex = 0;
let endIndex = array.length - 1;
while (startIndex <= endIndex) {
const middleIndex = Math.floor((startIndex + endIndex) / 2);
const middleValue = array[middleIndex];
if (middleValue === number) {
console.log(`Found at index ${middleIndex}`);
} else if (middleValue < number) {
startIndex = middleIndex + 1;
} else {
endIndex = middleIndex - 1;
}
}
}
O(logn)
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
O(logn) - логарифмическая
Количествоопераций
Размер входных данных, ед.
1 100 1000 10000
1
100
1000
10000
O(logn) - логарифмическая
2el => 1
4el => 2
8el => 3
1000el => ~10
10000el => ~13
100000el => ~16
Количествоопераций
Бинарное
Дерево
1
13
9 54 11
6
70
Бинарное
Дерево
1
3
9 54 11
6
70
Бинарное
Дерево
1
3
5 54 11
6
70
Бинарное
Дерево
1
3
5 54 71
6
70
Поиск. Бинарное дерево
class Node {
constructor(value) {
this.value = value;
this.connections = [];
}
addConnection(node) {
this.connections.push(node);
}
}
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class Tree {
constructor() {
this.root = null;
}
}
class Tree {
constructor() {
this.root = null
}
insert(data) {
const newNode = new Node(data);
if (this.root === null) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
}
}
Бинарное дерево
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
insertNode(parentNode = this.head, newNode) {
if (newNode.data < parentNode.data) {
if (parentNode.left === null) parentNode.left = newNode;
else {
this.insertNode(parentNode.left, newNode);
}
} else {
if (parentNode.right === null) parentNode.right = newNode;
else {
this.insertNode(parentNode.right, newNode);
}
}
}
Алгоритмы
1. Поиск
2. Сортировки
Сортировка Пузырьком
(bubble sort)
O(n^2)
Сортировка Пузырьком
(bubble sort)
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
function bubble(arr) {
const length = arr.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length - i - 1; j++) {
const current = arr[j];
const next = arr[j + 1];
if (current > next) {
arr[j] = next;
arr[j + 1] = current;
}
}
}
return arr;
}
Сортировка слиянием
(Merge sort)
O(n * logn)
Сортировка слиянием
(Merge sort)
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function mergeSort(unsortedArray) {
if (unsortedArray.length <= 1) {
return unsortedArray;
}
const middle = Math.floor(unsortedArray.length / 2);
const left = unsortedArray.slice(0, middle);
const right = unsortedArray.slice(middle);
return merge(
mergeSort(left), mergeSort(right)
);
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
function merge(left, right) {
const resultArray = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
resultArray.push(left[leftIndex]);
leftIndex++;
} else {
resultArray.push(right[rightIndex]);
rightIndex++;
}
}
return resultArray
.concat(left.slice(leftIndex))
.concat(right.slice(rightIndex));
}
Память vs. Время
Bogosort
(самая неэффективная сортировка)
O(n * n!)Bogosort
(самая неэффективная сортировка)
Уже хорошо
работает
Array.sort()
Уже хорошо
работает
Array.sort()
Разные имплементации в
разных браузерах. (и в
разных версиях).
Уже хорошо
работает
Array.sort()
Разные имплементации в
разных браузерах. (и в
разных версиях).
В целом, базируется на
сортировках слиянием и
быстрой сортировке (в
зависимости от типа данных в
массиве).
Уже хорошо
работает
Array.sort()
Разные имплементации в
разных браузерах. (и в
разных версиях).
В целом, базируется на
сортировках слиянием и
быстрой сортировке (в
зависимости от типа данных в
массиве).
+ на небольших массивах (до
10 элементов) используется
сортировка вставками.
Заключение
Заключение
● Вам не нужно знать все алгоритмы и структуры данных. Самые
необходимые знания, дающие больше всего пользы, в то же
время являются и самыми простыми в освоении.
Заключение
● Вам не нужно знать все алгоритмы и структуры данных. Самые
необходимые знания, дающие больше всего пользы, в то же
время являются и самыми простыми в освоении.
● Нет необходимости помнить все реализации, вы даже можете
забыть какие-то самые важные. Достаточно один раз
разобраться в них, чтобы иметь представление о возможностях.
Заключение
● Вам не нужно знать все алгоритмы и структуры данных. Самые
необходимые знания, дающие больше всего пользы, в то же
время являются и самыми простыми в освоении.
● Нет необходимости помнить все реализации, вы даже можете
забыть какие-то самые важные. Достаточно один раз
разобраться в них, чтобы иметь представление о возможностях.
● Анализируйте ваши алгоритмы. Задумывайтесь над их
эффективностью. Чем эффективнее код вы создаете, тем
производительнее и надежнее будет ваш продукт (и тем круче
вы станете как разработчик)
Материалы
Теория
● Оценка Сложности алгоритма
● Асимптотический анализ алгоритмов
● Структуры данных для самых маленьких
● The complexity of simple algorithms and data structures in JS
● Introduction to Data Structures and Algorithms
Практика
● Data Structures
● Fundamentals of Algorithms
● HackerRank
Q&A
Слайды
Telegram - @adam4leos
LinkedIn - Adam Leos
adam.leos@pm.me
Контакты

Mais conteúdo relacionado

Mais procurados

Лекция 4. Стеки и очереди
Лекция 4. Стеки и очередиЛекция 4. Стеки и очереди
Лекция 4. Стеки и очередиMikhail Kurnosov
 
Лекция 1. Анализ эффективности алгоритмов
Лекция 1. Анализ эффективности алгоритмовЛекция 1. Анализ эффективности алгоритмов
Лекция 1. Анализ эффективности алгоритмовMikhail Kurnosov
 
Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)
Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)
Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)Mikhail Kurnosov
 
Лекция 1. Амортизационный анализ (amortized analysis)
Лекция 1. Амортизационный анализ (amortized analysis)Лекция 1. Амортизационный анализ (amortized analysis)
Лекция 1. Амортизационный анализ (amortized analysis)Mikhail Kurnosov
 
Лекция 10. Графы. Остовные деревья минимальной стоимости
Лекция 10. Графы. Остовные деревья минимальной стоимостиЛекция 10. Графы. Остовные деревья минимальной стоимости
Лекция 10. Графы. Остовные деревья минимальной стоимостиMikhail Kurnosov
 
20100930 proof complexity_hirsch_lecture03
20100930 proof complexity_hirsch_lecture0320100930 proof complexity_hirsch_lecture03
20100930 proof complexity_hirsch_lecture03Computer Science Club
 
Лекция 7: Бинарные кучи (пирамиды)
Лекция 7: Бинарные кучи (пирамиды)Лекция 7: Бинарные кучи (пирамиды)
Лекция 7: Бинарные кучи (пирамиды)Mikhail Kurnosov
 
Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)
Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)
Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)Mikhail Kurnosov
 
Python. Объектно-ориентированное программирование
Python. Объектно-ориентированное программирование Python. Объектно-ориентированное программирование
Python. Объектно-ориентированное программирование Theoretical mechanics department
 
практика 15
практика 15практика 15
практика 15student_kai
 
Лекция 1: Введение в алгоритмы
Лекция 1: Введение в алгоритмыЛекция 1: Введение в алгоритмы
Лекция 1: Введение в алгоритмыMikhail Kurnosov
 
Использование GNU OCTAVE для инженерных и математических расчетов
Использование GNU OCTAVE для инженерных и математических расчетовИспользование GNU OCTAVE для инженерных и математических расчетов
Использование GNU OCTAVE для инженерных и математических расчетовТранслируем.бел
 
Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...
Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...
Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...Nikolay Grebenshikov
 
Основы языка Питон: типы данных, операторы
Основы языка Питон: типы данных, операторыОсновы языка Питон: типы данных, операторы
Основы языка Питон: типы данных, операторыTheoretical mechanics department
 
ITMO RecSys course. Autumn 2014. Lecture 6
ITMO RecSys course. Autumn 2014. Lecture 6ITMO RecSys course. Autumn 2014. Lecture 6
ITMO RecSys course. Autumn 2014. Lecture 6Andrey Danilchenko
 

Mais procurados (20)

Лекция 4. Стеки и очереди
Лекция 4. Стеки и очередиЛекция 4. Стеки и очереди
Лекция 4. Стеки и очереди
 
Основы SciPy
Основы SciPyОсновы SciPy
Основы SciPy
 
Лекция 1. Анализ эффективности алгоритмов
Лекция 1. Анализ эффективности алгоритмовЛекция 1. Анализ эффективности алгоритмов
Лекция 1. Анализ эффективности алгоритмов
 
Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)
Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)
Лекция 6. Фибоначчиевы кучи (Fibonacci heaps)
 
Лекция 1. Амортизационный анализ (amortized analysis)
Лекция 1. Амортизационный анализ (amortized analysis)Лекция 1. Амортизационный анализ (amortized analysis)
Лекция 1. Амортизационный анализ (amortized analysis)
 
Лекция 10. Графы. Остовные деревья минимальной стоимости
Лекция 10. Графы. Остовные деревья минимальной стоимостиЛекция 10. Графы. Остовные деревья минимальной стоимости
Лекция 10. Графы. Остовные деревья минимальной стоимости
 
20100930 proof complexity_hirsch_lecture03
20100930 proof complexity_hirsch_lecture0320100930 proof complexity_hirsch_lecture03
20100930 proof complexity_hirsch_lecture03
 
Лекция 7: Бинарные кучи (пирамиды)
Лекция 7: Бинарные кучи (пирамиды)Лекция 7: Бинарные кучи (пирамиды)
Лекция 7: Бинарные кучи (пирамиды)
 
Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)
Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)
Лекция 7: Очереди с приоритетами. Бинарные кучи (пирамиды)
 
Синтез функциональных программ при помощи метода дедуктивных таблиц
Синтез функциональных программ при помощи метода дедуктивных таблицСинтез функциональных программ при помощи метода дедуктивных таблиц
Синтез функциональных программ при помощи метода дедуктивных таблиц
 
Python. Объектно-ориентированное программирование
Python. Объектно-ориентированное программирование Python. Объектно-ориентированное программирование
Python. Объектно-ориентированное программирование
 
практика 15
практика 15практика 15
практика 15
 
Лекция 1: Введение в алгоритмы
Лекция 1: Введение в алгоритмыЛекция 1: Введение в алгоритмы
Лекция 1: Введение в алгоритмы
 
Использование GNU OCTAVE для инженерных и математических расчетов
Использование GNU OCTAVE для инженерных и математических расчетовИспользование GNU OCTAVE для инженерных и математических расчетов
Использование GNU OCTAVE для инженерных и математических расчетов
 
Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...
Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...
Лекция №15. Методы программирования. Предмет "Структуры и алгоритмы обработки...
 
Python
PythonPython
Python
 
Основы NumPy
Основы NumPyОсновы NumPy
Основы NumPy
 
Основы языка Питон: типы данных, операторы
Основы языка Питон: типы данных, операторыОсновы языка Питон: типы данных, операторы
Основы языка Питон: типы данных, операторы
 
Python: Модули и пакеты
Python: Модули и пакетыPython: Модули и пакеты
Python: Модули и пакеты
 
ITMO RecSys course. Autumn 2014. Lecture 6
ITMO RecSys course. Autumn 2014. Lecture 6ITMO RecSys course. Autumn 2014. Lecture 6
ITMO RecSys course. Autumn 2014. Lecture 6
 

Semelhante a JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Data Structures in Front-end, anyway

чернякова г.в.
чернякова г.в.чернякова г.в.
чернякова г.в.sharikdp
 
JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...
JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...
JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...JSFestUA
 
Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"
Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"
Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"Fwdays
 
DSLs in Lisp and Clojure
DSLs in Lisp and ClojureDSLs in Lisp and Clojure
DSLs in Lisp and ClojureVasil Remeniuk
 
Математическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принциповМатематическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принциповetyumentcev
 
2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципы
2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципы2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципы
2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципыHappyDev
 
Use of eliptic curves for generating digital signature
Use of eliptic curves for generating digital signatureUse of eliptic curves for generating digital signature
Use of eliptic curves for generating digital signatureAndrei Poliakov
 
Sergii Tsypanov "Performance 1001 Tips"
Sergii Tsypanov "Performance 1001 Tips"Sergii Tsypanov "Performance 1001 Tips"
Sergii Tsypanov "Performance 1001 Tips"LogeekNightUkraine
 
Как написать JIT компилятор
Как написать JIT компиляторКак написать JIT компилятор
Как написать JIT компиляторAndrew Aksyonoff
 
разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3etyumentcev
 
разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3Eugeniy Tyumentcev
 
07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...
07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...
07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...HappyDev-lite
 
2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?
2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?
2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?HappyDev
 
Структуры данных в JavaScript | Odessa Frontend Meetup #13
Структуры данных в JavaScript | Odessa Frontend Meetup #13Структуры данных в JavaScript | Odessa Frontend Meetup #13
Структуры данных в JavaScript | Odessa Frontend Meetup #13OdessaFrontend
 
презентация
презентацияпрезентация
презентацияLIANA180
 
Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...
Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...
Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...Yandex
 

Semelhante a JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Data Structures in Front-end, anyway (20)

чернякова г.в.
чернякова г.в.чернякова г.в.
чернякова г.в.
 
Algo 01 part01
Algo 01 part01Algo 01 part01
Algo 01 part01
 
JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...
JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...
JS Fest 2019. Владимир Агафонкин. Быстро по умолчанию: алгоритмическое мышлен...
 
Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"
Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"
Aleksei Milovidov "Let's optimize one aggregate function in ClickHouse"
 
Java 8 puzzlers
Java 8 puzzlersJava 8 puzzlers
Java 8 puzzlers
 
DSLs in Lisp and Clojure
DSLs in Lisp and ClojureDSLs in Lisp and Clojure
DSLs in Lisp and Clojure
 
Математическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принциповМатематическое обоснование S.O.L.I.D принципов
Математическое обоснование S.O.L.I.D принципов
 
Step cpp022
Step cpp022Step cpp022
Step cpp022
 
2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципы
2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципы2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципы
2014.12.06 04 Евгений Тюменцев — Откуда появились s.o.l.i.d. принципы
 
Use of eliptic curves for generating digital signature
Use of eliptic curves for generating digital signatureUse of eliptic curves for generating digital signature
Use of eliptic curves for generating digital signature
 
Sergii Tsypanov "Performance 1001 Tips"
Sergii Tsypanov "Performance 1001 Tips"Sergii Tsypanov "Performance 1001 Tips"
Sergii Tsypanov "Performance 1001 Tips"
 
Как написать JIT компилятор
Как написать JIT компиляторКак написать JIT компилятор
Как написать JIT компилятор
 
разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3
 
разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3разработка серверов и серверных приложений лекция №3
разработка серверов и серверных приложений лекция №3
 
07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...
07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...
07 HappyDev-lite-2015 spring. Евгений Тюменцев. Зачем программисту нужно зна...
 
2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?
2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?
2015-04-12 07 Евгений Тюменцев. Зачем программисту нужно знать математику?
 
паскаль
паскальпаскаль
паскаль
 
Структуры данных в JavaScript | Odessa Frontend Meetup #13
Структуры данных в JavaScript | Odessa Frontend Meetup #13Структуры данных в JavaScript | Odessa Frontend Meetup #13
Структуры данных в JavaScript | Odessa Frontend Meetup #13
 
презентация
презентацияпрезентация
презентация
 
Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...
Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...
Евгений Крутько — Опыт внедрения технологий параллельных вычислений для повыш...
 

Mais de JSFestUA

JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in productionJS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in productionJSFestUA
 
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript PerformanceJS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript PerformanceJSFestUA
 
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"JSFestUA
 
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...JSFestUA
 
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...JSFestUA
 
JS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstackJS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstackJSFestUA
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JSFestUA
 
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...JSFestUA
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJSFestUA
 
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...JSFestUA
 
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?JSFestUA
 
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the ScaleJS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the ScaleJSFestUA
 
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratchJS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratchJSFestUA
 
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотятJS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотятJSFestUA
 
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for RustJS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for RustJSFestUA
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JSFestUA
 
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проектіJS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проектіJSFestUA
 
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядроJS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядроJSFestUA
 
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...JSFestUA
 
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJSFestUA
 

Mais de JSFestUA (20)

JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in productionJS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
JS Fest 2019/Autumn. Роман Савіцький. Webcomponents & lit-element in production
 
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript PerformanceJS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
JS Fest 2019/Autumn. Erick Wendel. 10 secrets to improve Javascript Performance
 
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
JS Fest 2019/Autumn. Alexandre Gomes. Embrace the "react fatigue"
 
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
JS Fest 2019/Autumn. Anton Cherednikov. Choreographic or orchestral architect...
 
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
JS Fest 2019/Autumn. Marko Letic. Saving the world with JavaScript: A Data Vi...
 
JS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstackJS Fest 2019/Autumn. Александр Товмач. JAMstack
JS Fest 2019/Autumn. Александр Товмач. JAMstack
 
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
JS Fest 2019/Autumn. Влад Федосов. Technology agnostic microservices at SPA f...
 
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
JS Fest 2019/Autumn. Дмитрий Жарков. Blockchainize your SPA or Integrate Java...
 
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developersJS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
JS Fest 2019/Autumn. Maciej Treder. Angular Schematics - Develop for developers
 
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
JS Fest 2019/Autumn. Kyle Boss. A Tinder Love Story: Create a Wordpress Blog ...
 
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
JS Fest 2019/Autumn. Андрей Старовойт. Зачем нужен тип "true" в TypeScript?
 
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the ScaleJS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
JS Fest 2019/Autumn. Eyal Eizenberg. Tipping the Scale
 
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratchJS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
JS Fest 2019/Autumn. Sota Ohara. Сreate own server less CMS from scratch
 
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотятJS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
JS Fest 2019/Autumn. Джордж Евтушенко. Как стать программистом, которого хотят
 
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for RustJS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
 
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проектіJS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
JS Fest 2019/Autumn. Андрей Андрийко. Гексагональна архітектура в Nodejs проекті
 
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядроJS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
JS Fest 2019/Autumn. Борис Могила. Svelte. Почему нам не нужно run-time ядро
 
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
JS Fest 2019/Autumn. Виталий Кухар. Сравнение кластеризации HTTP, TCP и UDP н...
 
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложениеJS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
JS Fest 2019. Виктор Турский. 6 способов взломать твое JavaScript приложение
 

JS Fest 2019/Autumn. Adam Leos. So why do you need to know Algorithms and Data Structures in Front-end, anyway

  • 1. So why do you need to know Algorithms and Data Structures in Front-end, anyway
  • 3. Adam Leos ● Старший разработчик PlutoTV
  • 4.
  • 5. Adam Leos ● Старший разработчик PlutoTV ● Автор веб-дополнения UnlimitedControl
  • 6.
  • 9. Adam Leos ● Старший разработчик PlutoTV ● Автор веб-дополнения UnlimitedControl ● Докладчик-идеолог
  • 10. Что вы видите, это не то, что исполняется ©
  • 11. Что вы видите, это не то, что исполняется © Нет плохого кода, а есть плохие компиляторы ©
  • 14. Сложность алгоритма Big O notation, O Omega notation, Ω
  • 15. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ
  • 16. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations
  • 17. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity
  • 18. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n)
  • 19. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n)
  • 20. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn)
  • 21. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn) logarithmic
  • 22. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn) logarithmic polynomial
  • 23. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn) logarithmic polynomial Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0 . }
  • 24. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn) logarithmic polynomial Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0 . } c and n0 are constants, f(n) and g(n) are functions over non-negative integers
  • 25. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn) logarithmic polynomial Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0 . } c and n0 are constants, f(n) and g(n) are functions over non-negative integers
  • 26. Сложность алгоритма Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn) logarithmic polynomial Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0 . } c and n0 are constants, f(n) and g(n) are functions over non-negative integers
  • 27. Algorithm Complexity Big O notation, O Omega notation, Ω Theta Notation, θ asymptotic notations, asymptotic complexity O(n) Ο(log n) O(n * logn) logarithmic polynomial Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0 . } c and n0 are constants, f(n) and g(n) are functions over non-negative integers
  • 29. Сложность алгоритма Как будет расти расход ресурсов* с увеличением размера входных данных.
  • 30. Сложность алгоритма Как будет расти расход ресурсов* с увеличением размера входных данных. * время и память
  • 31. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; }
  • 32. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; }
  • 33. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; }
  • 34. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; }
  • 35. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; }
  • 36. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; }
  • 37. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; } sumNumbersInArray([1, 2, 3, 4, 5]);
  • 38. Сложность алгоритма function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; } sumNumbersInArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
  • 39. Сложность алгоритма Как будет расти расход ресурсов* с увеличением размера входных данных. * время и память
  • 42. Big O notation, O Функция, которая описывает рост сложности алгоритма.
  • 43. Big O notation, O function sumNumbersInArray(array) { let sum = 0; array.forEach(number => sum += number); return sum; }
  • 50. Размер входных данных, ед. 1 100 1000 10000 Количествоопераций
  • 51. Размер входных данных, ед. 1 100 1000 10000 Количествоопераций 1 100 1000 10000
  • 52. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 Количествоопераций
  • 53. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 O(n) Количествоопераций
  • 54. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 O(n) - линейная Количествоопераций
  • 55. Big O function simpleCalculate() { const a = 1 + 2; const b = 3 + 4; console.log('calculating...'); return b - a; } simpleCalculate();
  • 56. Big O function simpleCalculate() { const a = 1 + 2; const b = 3 + 4; console.log('calculating...'); return b - a; } simpleCalculate(); O(1)
  • 57. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 O(1) Количествоопераций
  • 58. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 O(1) - константная (постоянная) Количествоопераций
  • 59. Big O function simpleCalculate(number) { const a = 1 + 2; const b = 3 + 4; console.log('calculating...'); return b - a + number; } simpleCalculate(8);
  • 60. Big O function simpleCalculate(number) { const a = 1 + 2; const b = 3 + 4; console.log('calculating...'); return b - a + number; } simpleCalculate(8); O(1)
  • 61. Big O function simpleCalculate(array) { const a = 1 + 2; const b = 3 + 4; let additionalNumber = 0; array.forEach(num => additionalNumber += num); return b - a + additionalNumber; } simpleCalculate([1, 2, 5, 10, 1223]);
  • 62. Big O function simpleCalculate(array) { const a = 1 + 2; const b = 3 + 4; let additionalNumber = 0; array.forEach(num => additionalNumber += num); return b - a + additionalNumber; } simpleCalculate([1, 2, 5, 10, 1223]); O(n)
  • 63. Big O function simpleCalculate(array) { const a = 1 + 2; const b = 3 + 4; const additionalNumber = array.length; return b - a + additionalNumber; } simpleCalculate([1, 2, 5, 10, 1223]);
  • 64. Big O function simpleCalculate(array) { const a = 1 + 2; const b = 3 + 4; const additionalNumber = array.length; return b - a + additionalNumber; } simpleCalculate([1, 2, 5, 10, 1223]); O(1)
  • 65. Big O function notSoSimpleCalculate(array) { for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { array[i] = array[i] + array[j]; } } return array; } notSoSimpleCalculate([1, 2, 3]);
  • 66. Big O function notSoSimpleCalculate(array) { for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { array[i] = array[i] + array[j]; } } return array; } notSoSimpleCalculate([1, 2, 3]); O(n^2)
  • 67. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 O(n^2) - квадратичная Количествоопераций
  • 68. Big O function notSoSimpleCalculate(array) { array.forEach(num => console.log(num)); for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { array[i] = array[i] + array[j]; } } return array; }
  • 69. Big O function notSoSimpleCalculate(array) { array.forEach(num => console.log(num)); for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { array[i] = array[i] + array[j]; } } return array; } O(n^2)
  • 70. Big O function mightBeSimpleCalculate(array) { let total = 0; array.forEach(num => { const additional = array.indexOf(num) > 5 ? 5 : 1; total = total + num + additional; }); return array; }
  • 71. Big O function mightBeSimpleCalculate(array) { let total = 0; array.forEach(num => { const additional = array.indexOf(num) > 5 ? 5 : 1; total = total + num + additional; }); return array; } O(n^2)
  • 72. Big O function mightBeSimpleCalculate(array) { let total = 0; array.forEach(num => { const additional = array.indexOf(num) > 5 ? 5 : 1; total = total + num + additional; }); return array; } O(n^2)
  • 73. Big O function mightBeSimpleCalculate(array) { let total = 0; array.forEach((num, index) => { const additional = index > 5 ? 5 : 1; total = total + num + additional; }); return array; } O(n)
  • 75. Пример роста в цифрах Входные данные - 10000 элементов
  • 76. Пример роста в цифрах O(1) - 1 Входные данные - 10000 элементов
  • 77. Пример роста в цифрах O(1) - 1 O(n) - 10000 Входные данные - 10000 элементов
  • 78. Пример роста в цифрах O(1) - 1 O(n) - 10000 O(n^2) - 100000000 (сто миллионов) Входные данные - 10000 элементов
  • 79. Пример роста в цифрах O(1) - 1 O(n) - 10000 O(n^2) - 100000000 (сто миллионов) O(n^3) - 1000000000000 (один триллион) Входные данные - 10000 элементов
  • 80. Пример роста в цифрах O(1) - 1 O(n) - 10000 O(n^2) - 100000000 (сто миллионов) O(n^3) - 1000000000000 (один триллион) O(n!) очень много 100000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000…… Входные данные - 10000 элементов
  • 81.
  • 83. Структуры данных Определенный способ организации данных для максимально эффективного использования
  • 84. Структуры данных ● Доступ (получить данные) ● Поиск (найти данные) ● Вставка (добавить данные) ● Удаление (удалить данные)
  • 85.
  • 88. Массивы const arr = [1, 2, 3]; arr[1]; // 2
  • 89. Массивы const arr = [1, 2, 3]; arr[1]; // 2 O(1)
  • 90. Массивы const arr = [1, 2, 3]; arr[1]; // 2 arr[2]; // 3 O(1) O(1)
  • 91. Массивы const arr = [1, 2, 3]; arr[1]; // 2 arr[2]; // 3 arr[9]; // undefined O(1) O(1) O(1)
  • 92. Массивы const arr = [1, 2, 3]; arr[1]; // 2 arr[2]; // 3 arr[9]; // undefined arr[0] = 4; // [4, 2, 3] O(1) O(1) O(1) O(1)
  • 93. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4]
  • 94. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4] O(1)*
  • 95. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4] arr.pop(); // [1, 2, 3] O(1)*
  • 96. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4] arr.pop(); // [1, 2, 3] O(1) O(1)*
  • 97. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4] arr.pop(); // [1, 2, 3] arr.shift(); // [2, 3] O(1) O(1)*
  • 98. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4] arr.pop(); // [1, 2, 3] arr.shift(); // [2, 3] O(1) O(n) O(1)*
  • 99. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4] arr.pop(); // [1, 2, 3] arr.shift(); // [2, 3] arr.unshift(4); // [4, 2, 3] O(1) O(n) O(1)*
  • 100. Массивы const arr = [1, 2, 3]; arr.push(4); // [1, 2, 3, 4] arr.pop(); // [1, 2, 3] arr.shift(); // [2, 3] arr.unshift(4); // [4, 2, 3] O(1) O(n) O(n) O(1)*
  • 104. Объекты const obj = { id: 1, name: 'Adam', };
  • 105. Объекты const obj = { id: 1, name: 'Adam', }; obj.id // 1
  • 106. Объекты const obj = { id: 1, name: 'Adam', }; obj.id // 1 O(1)
  • 107. Объекты const obj = { id: 1, name: 'Adam', }; obj.id // 1 obj['name'] // 1 O(1) O(1)
  • 108. Объекты const obj = { id: 1, name: 'Adam', }; obj.surname = 'Leos'; obj['name'] = []; O(1) O(1)
  • 109. Объекты const obj = { id: 1, name: 'Adam', }; Object.keys(obj) // ['id', 'name'] Object.values(obj) // [1, 'Adam']
  • 110. Объекты const obj = { id: 1, name: 'Adam', }; Object.keys(obj) // ['id', 'name'] Object.values(obj) // [1, 'Adam'] O(n) O(n)
  • 112. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 113. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 114. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 115. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 116. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 117. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 118. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 119. Объекты function countSymbols(string) { const dict = {}; for (let i = 0; i < string.length; i++) { const iterableSymbol = string[i]; if (dict[iterableSymbol] === undefined) dict[iterableSymbol] = 0; dict[iterableSymbol]++; } return dict; } Посчитать символы в строке
  • 120. Объекты countSymbols('adam') // Object { a: 2, d: 1, m: 1 } countSymbols('mississippi') // Object { m: 1, i: 4, s: 4, p: 2 } Посчитать символы в строке
  • 122.
  • 123. const shows = [ { id: 1, name: 'Rick and Morty', categories: [ 'Comedy', 'Animated', 'Science', ], data: 1001010101001011, }, {/.../}, {/.../}, {/.../}, {/.../}, ];
  • 124. const shows = [ { id: 1, name: 'Rick and Morty', categories: [ 'Comedy', 'Animated', 'Science', ], data: 1001010101001011, }, {/.../}, {/.../}, {/.../}, {/.../}, ]; const bannedShows = [ { id: 1, name: 'Rick and Morty', categories: [ 'Comedy', 'Animated', 'Science', ], }, {/.../}, ];
  • 125. function ineffectiveBanning(shows) { shows.forEach(show => { const { id: showID } = show; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; if (showID === bannedShowID) { show.isBanned = true; }; }); }); };
  • 126. function ineffectiveBanning(shows) { shows.forEach(show => { const { id: showID } = show; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; if (showID === bannedShowID) { show.isBanned = true; }; }); }); };
  • 127. function ineffectiveBanning(shows) { shows.forEach(show => { const { id: showID } = show; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; if (showID === bannedShowID) { show.isBanned = true; }; }); }); };
  • 128. function ineffectiveBanning(shows) { shows.forEach(show => { const { id: showID } = show; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; if (showID === bannedShowID) { show.isBanned = true; }; }); }); };
  • 129. function ineffectiveBanning(shows) { shows.forEach(show => { const { id: showID } = show; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; if (showID === bannedShowID) { show.isBanned = true; }; }); }); };
  • 130. function ineffectiveBanning(shows) { shows.forEach(show => { const { id: showID } = show; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; if (showID === bannedShowID) { show.isBanned = true; }; }); }); };
  • 131. function ineffectiveBanning(shows) { shows.forEach(show => { const { id: showID } = show; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; if (showID === bannedShowID) { show.isBanned = true; }; }); }); };
  • 132. function effectiveBanning(shows) { const bannedShowsIDMap = {}; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; bannedShowsIDMap[bannedShowID] = true; }; shows.forEach(show => { const { id: showID } = show; if (bannedShowsIDMap[showID]) show.isBanned = true; }); };
  • 133. function effectiveBanning(shows) { const bannedShowsIDMap = {}; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; bannedShowsIDMap[bannedShowID] = true; }; shows.forEach(show => { const { id: showID } = show; if (bannedShowsIDMap[showID]) show.isBanned = true; }); };
  • 134. function effectiveBanning(shows) { const bannedShowsIDMap = {}; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; bannedShowsIDMap[bannedShowID] = true; }; shows.forEach(show => { const { id: showID } = show; if (bannedShowsIDMap[showID]) show.isBanned = true; }); };
  • 135. function effectiveBanning(shows) { const bannedShowsIDMap = {}; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; bannedShowsIDMap[bannedShowID] = true; }; shows.forEach(show => { const { id: showID } = show; if (bannedShowsIDMap[showID]) show.isBanned = true; }); };
  • 136. function effectiveBanning(shows) { const bannedShowsIDMap = {}; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; bannedShowsIDMap[bannedShowID] = true; }; shows.forEach(show => { const { id: showID } = show; if (bannedShowsIDMap[showID]) show.isBanned = true; }); };
  • 137. function effectiveBanning(shows) { const bannedShowsIDMap = {}; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; bannedShowsIDMap[bannedShowID] = true; }; shows.forEach(show => { const { id: showID } = show; if (bannedShowsIDMap[showID]) show.isBanned = true; }); };
  • 138. function effectiveBanning(shows) { const bannedShowsIDMap = {}; bannedShows.forEach(bannedShow => { const { id: bannedShowID } = bannedShow; bannedShowsIDMap[bannedShowID] = true; }; shows.forEach(show => { const { id: showID } = show; if (bannedShowsIDMap[showID]) show.isBanned = true; }); }; x100
  • 140. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 141. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 142. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 143. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 144. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 145. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 146. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 147. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels .filter(filterEmptyTimelines) .map(addIdentificator) .map(modifyImages) .map(removeParams) .map(setSession) // more code }
  • 148. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels.reduce((acc, channel) => { if (hasEmptyTimelines(channel.timelines)) { return acc; } const enchancedChannel = setChannelURL(reduceImagesObject(addIDToChannel(channel))); acc.push(enchancedChannel); return acc; }, []); // more code }
  • 149. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels.reduce((acc, channel) => { if (hasEmptyTimelines(channel.timelines)) { return acc; } const enchancedChannel = setChannelURL(reduceImagesObject(addIDToChannel(channel))); acc.push(enchancedChannel); return acc; }, []); // more code }
  • 150. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels.reduce((acc, channel) => { if (hasEmptyTimelines(channel.timelines)) { return acc; } const enchancedChannel = setChannelURL(reduceImagesObject(addIDToChannel(channel))); acc.push(enchancedChannel); return acc; }, []); // more code }
  • 151. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels.reduce((acc, channel) => { if (hasEmptyTimelines(channel.timelines)) { return acc; } const enchancedChannel = setChannelURL(reduceImagesObject(addIDToChannel(channel))); acc.push(enchancedChannel); return acc; }, []); // more code }
  • 152. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels.reduce((acc, channel) => { if (hasEmptyTimelines(channel.timelines)) { return acc; } const enchancedChannel = setChannelURL(reduceImagesObject(addIDToChannel(channel))); acc.push(enchancedChannel); return acc; }, []); // more code }
  • 153. function enchanceApiResponse(apiResponse) { const channels = apiResponse.channels.reduce((acc, channel) => { if (hasEmptyTimelines(channel.timelines)) { return acc; } const enchancedChannel = setChannelURL(reduceImagesObject(addIDToChannel(channel))); acc.push(enchancedChannel); return acc; }, []); // more code } 10-30%
  • 161. Граф 1 13 9 54 11 6 70 Value (data) = 6 Connections = [13, 70]
  • 162. node = { value: 6, connections: [13, 70], }
  • 163. node = { value: 6, connections: [13, 70], } class Node { }
  • 164. node = { value: 6, connections: [13, 70], } class Node { constructor(value) { this.value = value; this.connections = []; } }
  • 165. class Node { constructor(value) { this.value = value; this.connections = []; } addConnection(node) { this.connections.push(node); } } node = { value: 6, connections: [13, 70], }
  • 166. class Node { constructor(value) { this.value = value; this.connections = []; } addConnection(node) { this.connections.push(node); } } node = { value: 6, connections: [13, 70], } const six = new Node(6);
  • 167. class Node { constructor(value) { this.value = value; this.connections = []; } addConnection(node) { this.connections.push(node); } } node = { value: 6, connections: [13, 70], } const six = new Node(6); six.value; // 6
  • 168. class Node { constructor(value) { this.value = value; this.connections = []; } addConnection(node) { this.connections.push(node); } } node = { value: 6, connections: [13, 70], } const six = new Node(6); six.value; // 6 const thirteen = new Node(13); const seventy = new Node(70);
  • 169. class Node { constructor(value) { this.value = value; this.connections = []; } addConnection(node) { this.connections.push(node); } } node = { value: 6, connections: [13, 70], } const six = new Node(6); six.value; // 6 const thirteen = new Node(13); const seventy = new Node(70); six.addConnection(thirteen); six.addConnection(seventy);
  • 170. class Node { constructor(value) { this.value = value; this.connections = []; } addConnection(node) { this.connections.push(node); } } node = { value: 6, connections: [13, 70], } const six = new Node(6); six.value; // 6 const thirteen = new Node(13); const seventy = new Node(70); six.addConnection(thirteen); six.addConnection(seventy); six.connections; // [{ value: 13, connections: [] }, { value: 70, connections: [] }];
  • 172. class Graph { constructor() { this.nodes = []; } }
  • 173. class Graph { constructor() { this.nodes = []; } addNode(node) { this.nodes.push(node); } }
  • 174. class Graph { constructor() { this.nodes = []; } addNode(node) { this.nodes.push(node); } addEdge(node1, node2) { node1.addConnection(node2); node2.addConnection(node1); }; }
  • 176. class Graph { constructor() { this.nodes = {}; } addNode(node) { this.nodes.push(node); } addEdge(node1, node2) { node1.addConnection(node2); node2.addConnection(node1); }; } const ourGraph = new Graph(); const one = new Node(1); const six = new Node(6); const nine = new Node(9); const eleven = new Node(11); const thirteen = new Node(13); const fiftyFour = new Node(54); const seventy = new Node(70);
  • 177. class Graph { constructor() { this.nodes = {}; } addNode(node) { this.nodes.push(node); } addEdge(node1, node2) { node1.addConnection(node2); node2.addConnection(node1); }; } ourGraph.addNode(one); ourGraph.addNode(six); ourGraph.addNode(nine); ourGraph.addNode(eleven); ourGraph.addNode(thirteen); ourGraph.addNode(fiftyFour); ourGraph.addNode(seventy); ourGraph.addEdge(one, thirteen); ourGraph.addEdge(nine, thirteen); ourGraph.addEdge(nine, fiftyFour); ourGraph.addEdge(thirteen, eleven); ourGraph.addEdge(thirteen, six); ourGraph.addEdge(six, seventy);
  • 178. Граф Гугл-карт Kharkiv - [Lviv]; Lviv - [Kharkiv, Odessa]; Odessa - [Lviv];
  • 179. Граф Гугл-карт Kharkiv - [Lviv]; Lviv - [Kharkiv, Odessa]; Odessa - [Lviv]; Seattle San Francisco Las Vegas Salt Lake City San Francisco
  • 180. Граф Гугл-карт Kharkiv - [Lviv]; Lviv - [Kharkiv, Odessa]; Odessa - [Lviv];
  • 181. const googleRoute = new Graph();
  • 182. const googleRoute = new Graph(); const seattle = new Node('Seattle'); const sanFrancisco = new Node('San Francisco'); const lasVegas = new Node('Las Vegas'); const saltLakeCity = new Node('Salt Lake City');
  • 183. const googleRoute = new Graph(); const seattle = new Node('Seattle'); const sanFrancisco = new Node('San Francisco'); const lasVegas = new Node('Las Vegas'); const saltLakeCity = new Node('Salt Lake City'); const seattleData = { name: 'Seattle', coordinates: [ 47.7471188, -125.6412592, ], state: 'WA', country: 'USA', weather: 'Sunny', /.../ };
  • 184. const googleRoute = new Graph(); const seattle = new Node('Seattle'); const sanFrancisco = new Node('San Francisco'); const lasVegas = new Node('Las Vegas'); const saltLakeCity = new Node('Salt Lake City'); googleRoute.addNode(seattle); googleRoute.addNode(sanFrancisco); googleRoute.addNode(lasVegas); googleRoute.addNode(saltLakeCity);
  • 185. const googleRoute = new Graph(); const seattle = new Node('Seattle'); const sanFrancisco = new Node('San Francisco'); const lasVegas = new Node('Las Vegas'); const saltLakeCity = new Node('Salt Lake City'); googleRoute.addNode(seattle); googleRoute.addNode(sanFrancisco); googleRoute.addNode(lasVegas); googleRoute.addNode(saltLakeCity); googleRoute.addEdge(seattle, sanFrancisco); googleRoute.addEdge(sanFrancisco, lasVegas); googleRoute.addEdge(lasVegas, saltLakeCity); googleRoute.addEdge(saltLakeCity, sanFrancisco);
  • 186. const googleRoute = new Graph(); const seattle = new Node('Seattle'); const sanFrancisco = new Node('San Francisco'); const lasVegas = new Node('Las Vegas'); const saltLakeCity = new Node('Salt Lake City'); googleRoute.addNode(seattle); googleRoute.addNode(sanFrancisco); googleRoute.addNode(lasVegas); googleRoute.addNode(saltLakeCity); googleRoute.addEdge(seattle, sanFrancisco); googleRoute.addEdge(sanFrancisco, lasVegas); googleRoute.addEdge(lasVegas, saltLakeCity); googleRoute.addEdge(saltLakeCity, sanFrancisco); sanFrancisco.connections = [ seattle, lasVegas, saltLakeCity, ];
  • 187. const googleRoute = new Graph(); const seattle = new Node('Seattle'); const sanFrancisco = new Node('San Francisco'); const lasVegas = new Node('Las Vegas'); const saltLakeCity = new Node('Salt Lake City'); googleRoute.addNode(seattle); googleRoute.addNode(sanFrancisco); googleRoute.addNode(lasVegas); googleRoute.addNode(saltLakeCity); googleRoute.addEdge(seattle, sanFrancisco); googleRoute.addEdge(sanFrancisco, lasVegas); googleRoute.addEdge(lasVegas, saltLakeCity); googleRoute.addEdge(saltLakeCity, sanFrancisco); sanFrancisco.connections = [ seattle, lasVegas, saltLakeCity, ]; seattle.connections = [ sanFrancisco ];
  • 192.
  • 193.
  • 194. Где еще используются графы 1. Сеть (маршрутизация данных). 2. Логистика (маршруты, направления). 3. Телекоммуникации (планирование частот вышек). 4. Социальные сети (возможные знакомые). 5. Рекомендации. 6. Схемы. 7. И еще очень много где.
  • 195. Структуры данных 1. Массивы 2. Объекты 3. Графы 4. Деревья
  • 201.
  • 202.
  • 204. const settings = { options: [ ], };
  • 205. const settings = { options: [ { }, { }, { }, // ... ], };
  • 206. const settings = { options: [ { name: 'video', options: [...], }, { name: 'sound', options: [...], }, { name: 'security', options: [...], }, // ... ], };
  • 207. const settings = { options: [ { name: 'video', options: [...], }, { name: 'sound', options: [...], }, { name: 'security', options: [...], }, // ... ], }; [ { name: 'subtitles', options: [...], }, { name: 'brightness', options: [...], }, // ... ];
  • 210. function find(number, array) { array.forEach((iterableNumber, index) => { if (iterableNumber === number) { console.log(`Found at index ${index}`); } }); }
  • 211. function find(number, array) { array.forEach((iterableNumber, index) => { if (iterableNumber === number) { console.log(`Found at index ${index}`); } }); } O(n)
  • 212. Поиск. Бинарный vs Последовательный
  • 213. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 214. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 215. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 216. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 217. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 218. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 219. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 220. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 221. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 222. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 223. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } }
  • 224. function binarySearch(number, array) { let startIndex = 0; let endIndex = array.length - 1; while (startIndex <= endIndex) { const middleIndex = Math.floor((startIndex + endIndex) / 2); const middleValue = array[middleIndex]; if (middleValue === number) { console.log(`Found at index ${middleIndex}`); } else if (middleValue < number) { startIndex = middleIndex + 1; } else { endIndex = middleIndex - 1; } } } O(logn)
  • 225. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 O(logn) - логарифмическая Количествоопераций
  • 226. Размер входных данных, ед. 1 100 1000 10000 1 100 1000 10000 O(logn) - логарифмическая 2el => 1 4el => 2 8el => 3 1000el => ~10 10000el => ~13 100000el => ~16 Количествоопераций
  • 232. class Node { constructor(value) { this.value = value; this.connections = []; } addConnection(node) { this.connections.push(node); } }
  • 233. class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } }
  • 234. class Tree { constructor() { this.root = null; } }
  • 235. class Tree { constructor() { this.root = null } insert(data) { const newNode = new Node(data); if (this.root === null) { this.root = newNode; } else { this.insertNode(this.root, newNode); } } }
  • 237. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 238. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 239. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 240. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 241. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 242. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 243. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 244. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 245. insertNode(parentNode = this.head, newNode) { if (newNode.data < parentNode.data) { if (parentNode.left === null) parentNode.left = newNode; else { this.insertNode(parentNode.left, newNode); } } else { if (parentNode.right === null) parentNode.right = newNode; else { this.insertNode(parentNode.right, newNode); } } }
  • 246.
  • 250. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 251. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 252. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 253. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 254. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 255. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 256. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 257. function bubble(arr) { const length = arr.length; for (let i = 0; i < length; i++) { for (let j = 0; j < length - i - 1; j++) { const current = arr[j]; const next = arr[j + 1]; if (current > next) { arr[j] = next; arr[j + 1] = current; } } } return arr; }
  • 259. O(n * logn) Сортировка слиянием (Merge sort)
  • 260. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 261. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 262. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 263. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 264. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 265. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 266. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 267. function mergeSort(unsortedArray) { if (unsortedArray.length <= 1) { return unsortedArray; } const middle = Math.floor(unsortedArray.length / 2); const left = unsortedArray.slice(0, middle); const right = unsortedArray.slice(middle); return merge( mergeSort(left), mergeSort(right) ); }
  • 268. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 269. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 270. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 271. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 272. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 273. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 274. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 275. function merge(left, right) { const resultArray = []; let leftIndex = 0; let rightIndex = 0; while (leftIndex < left.length && rightIndex < right.length) { if (left[leftIndex] < right[rightIndex]) { resultArray.push(left[leftIndex]); leftIndex++; } else { resultArray.push(right[rightIndex]); rightIndex++; } } return resultArray .concat(left.slice(leftIndex)) .concat(right.slice(rightIndex)); }
  • 278. O(n * n!)Bogosort (самая неэффективная сортировка)
  • 280. Уже хорошо работает Array.sort() Разные имплементации в разных браузерах. (и в разных версиях).
  • 281. Уже хорошо работает Array.sort() Разные имплементации в разных браузерах. (и в разных версиях). В целом, базируется на сортировках слиянием и быстрой сортировке (в зависимости от типа данных в массиве).
  • 282. Уже хорошо работает Array.sort() Разные имплементации в разных браузерах. (и в разных версиях). В целом, базируется на сортировках слиянием и быстрой сортировке (в зависимости от типа данных в массиве). + на небольших массивах (до 10 элементов) используется сортировка вставками.
  • 284. Заключение ● Вам не нужно знать все алгоритмы и структуры данных. Самые необходимые знания, дающие больше всего пользы, в то же время являются и самыми простыми в освоении.
  • 285. Заключение ● Вам не нужно знать все алгоритмы и структуры данных. Самые необходимые знания, дающие больше всего пользы, в то же время являются и самыми простыми в освоении. ● Нет необходимости помнить все реализации, вы даже можете забыть какие-то самые важные. Достаточно один раз разобраться в них, чтобы иметь представление о возможностях.
  • 286. Заключение ● Вам не нужно знать все алгоритмы и структуры данных. Самые необходимые знания, дающие больше всего пользы, в то же время являются и самыми простыми в освоении. ● Нет необходимости помнить все реализации, вы даже можете забыть какие-то самые важные. Достаточно один раз разобраться в них, чтобы иметь представление о возможностях. ● Анализируйте ваши алгоритмы. Задумывайтесь над их эффективностью. Чем эффективнее код вы создаете, тем производительнее и надежнее будет ваш продукт (и тем круче вы станете как разработчик)
  • 287. Материалы Теория ● Оценка Сложности алгоритма ● Асимптотический анализ алгоритмов ● Структуры данных для самых маленьких ● The complexity of simple algorithms and data structures in JS ● Introduction to Data Structures and Algorithms Практика ● Data Structures ● Fundamentals of Algorithms ● HackerRank
  • 288. Q&A Слайды Telegram - @adam4leos LinkedIn - Adam Leos adam.leos@pm.me Контакты