Sorting Algos Flashcards
merge sort
function mergeArrs(arr1, arr2) {
let result = [];
let i = 0;
let j = 0;
while (i < arr1.length && j < arr2.length) { if (arr1[i] < arr2[j]) { result.push(arr1[i]); i++; } if (arr2[j] < arr1[i]) { result.push(arr2[j]); j++ } } while (i < arr1.length) { result.push(arr1[i]); i++ } while (j < arr2.length) { result.push(arr2[j]); j++; } return result; }
merge sort runtime
O(n*log n)
insertion sort
function insertion(arr) { for (let i = 0; i < arr.length; i++) { let key = arr[i]; let j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } return arr; }
insertion sort runtime
0(n*n)
Pathfinding and Maze Solving
DFS
Detecting Cycles in Graphs
DFS
Connected Components in Graphs
DFS
Topological Sorting (push to stack after visiting all dependencies)
DFS post-order
Solving Puzzles and Backtracking
DFS, backtracks when it finds deadends
Binary Tree Traversal
DFS
Binary Tree Traversal: Preorder
DFS, process root first
Binary Tree Traversal: inorder
DFS, process left subtree first
Binary Tree Traversal: postorder
DFS, process root last
Solving Island Problems in Grids
DFS, explore each island, traverse adjacent cells in multiple directions