Skip to content

Instantly share code, notes, and snippets.

View kshirish's full-sized avatar
👨‍💻

k kshirish

👨‍💻
View GitHub Profile
@kshirish
kshirish / dfs.js
Created August 12, 2024 12:44
N-ary Tree
// Creating a sample n-ary tree
// 1
// / | \
// 2 3 4
// / \ |
// 5 6 7
class NaryTreeNode {
constructor(value) {
this.value = value;
@kshirish
kshirish / bfs.js
Created August 12, 2024 12:42
N-ary Tree
// Creating a sample n-ary tree
// 1
// / | \
// 2 3 4
// / \ |
// 5 6 7
class NaryTreeNode {
constructor(value) {
this.value = value;
@kshirish
kshirish / dfs.js
Last active August 12, 2024 12:40
Binary Tree (BT)
// Root
// |
// |
// 11 12
// | |
// | |
// 13 14 15 16
// |
// |
// 17 18
@kshirish
kshirish / bfs.js
Last active August 12, 2024 12:39
Binary Tree (BT)
// Root
// |
// |
// 11 12
// | |
// | |
// 13 14 15 16
// |
// |
// 17 18
function mergeSort(array) {
if (array.length <= 1) {
return array; // Base case: arrays with 0 or 1 elements are already sorted
}
const mid = Math.floor(array.length / 2); // Find the middle index
const left = array.slice(0, mid); // Divide the array into two halves
const right = array.slice(mid);
// Recursively sort both halves and then merge them
function binarySearch(arr, value) {
let leftIndex = 0;
let rightIndex = arr.length - 1;
while(leftIndex <= rightIndex) {
let middleIndex = Math.floor((leftIndex + rightIndex)/2);
if(arr[middleIndex] === value) {
return middleIndex;
} else if(arr[middleIndex] < value) {
function quickSort(arr) {
if(arr.length <= 1) {
return arr;
}
let leftArr = [];
let rightArr = [];
const pivot = arr[arr.length - 1];
for (let index = 0; index < arr.length - 1; index++) {
function insertionSort(arr) {
for(let i = 1; i < arr.length; i += 1) {
let temp = arr[i];
for(let j = i - 1; j >= 0; j -= 1) {
if(arr[j] > temp) {
arr[j+1] = arr[j];
arr[j] = temp;
} else {
// arr[j+1] = temp;
function selectionSort(arr) {
for(let i = 0; i < arr.length - 1; i += 1) { // how many times
let min_index = i;
for(let j = i + 1; j < arr.length; j += 1) { // starts from where
if(arr[j] < arr[min_index]) {
min_index = j;
}
}
function bubbleSort(arr) {
for(let i = 0; i < arr.length - 1; i += 1) { // how many times
let swapped = false;
for(let j = 0; j < arr.length - 1 - i; j += 1) { // till where
if(arr[j + 1] < arr[j]) {
[arr[j + 1], arr[j]] = [arr[j], arr[j + 1]];
swapped = true;
}