Skip to content

Instantly share code, notes, and snippets.

View kshirish's full-sized avatar
👨‍💻

k kshirish

👨‍💻
View GitHub Profile
@kshirish
kshirish / linkedlist.js
Last active August 11, 2024 04:22
with head & tail
// 2 -> 8 -> 10 -> 4 -> 7
// {value, next}
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
// 2 <-> 8 <-> 10 <-> 4 <-> 3 <-> 6 <-> 7
// {prev, value, next}
class Node {
constructor(value) {
this.prev = null;
this.value = value;
this.next = null;
// 2, 8, 10, 4, 3, 6, 7
class Queue {
constructor() {
this.list = [];
this.pointer = 0;
}
enqueue(value) {
this.list.push(value);
// 2, 8, 10, 4, 3, 6, 7
class Stack {
constructor() {
this.list = [];
this.pointer = 0;
}
push(value) {
this.list.push(value);
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;
}
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 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 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 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 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