Last active
March 9, 2024 05:13
-
-
Save prathamesh-dukare/cb14bf4ec54f738b605f7fdabb9dea92 to your computer and use it in GitHub Desktop.
some simple cp problems and algorithms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. reverse an array | |
let a = [1, 2, 3, 4]; | |
let len = a.length; | |
for (let i = 0; i < len / 2; i++) { | |
let startIndex = i; | |
let endIndex = len - 1 - i; | |
let temp = a[startIndex]; | |
a[startIndex] = a[endIndex]; | |
a[endIndex] = temp; | |
} | |
console.log(a); | |
// can also do with logging in reverse manner but this is best apparoch | |
// 2. swap the numbred variables | |
let a = 1; | |
let b = 2; | |
a = a + b; | |
b = a - b; | |
a = a - b; | |
console.log(a, b); | |
// algo : bubble sort | |
let arr = [3, 5, 6, 1, 2]; | |
for (let i = 0; i <= arr.length - 1; i++) { | |
let currentMin = arr[i]; | |
for (let j = i + 1; j <= arr.length; j++) { | |
if (arr[j] < currentMin) { | |
currentMin = arr[j]; | |
let temp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = temp; | |
} | |
} | |
} | |
console.log(arr); // [1, 2, 3, 5, 6] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment