Last active
July 24, 2020 11:27
-
-
Save behnammodi/edd17a99ea4a5edbfabd2bed7b63b89f to your computer and use it in GitHub Desktop.
Algorithmes
This file contains 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
/* | |
* Commons array | |
* when array is sorted | |
*/ | |
function commons(a, b) { | |
const result = []; | |
let i = j = 0; | |
cancel:while (true) { | |
if (a[i] > b[j]) j++; | |
else if (a[i] < b[j]) i++; | |
else { | |
result.push(a[i]); | |
i++; | |
j++; | |
} | |
if(i === a.length || j === b.length) break cancel; | |
} | |
return result; | |
} | |
/* | |
* Multiple | |
* with sum recursive | |
*/ | |
function multiple(a, b) { | |
if (b === 0) return 0; | |
return multiple(a, b - 1) + a; | |
} | |
/* | |
* Factorielle | |
* https://fr.wikipedia.org/wiki/Factorielle | |
*/ | |
function factorielle(n) { | |
if (n === 0) return 1; | |
return n * factorielle(n - 1); | |
} | |
/* | |
* Binary Search | |
* https://fa.wikipedia.org/wiki/%D8%A7%D9%84%DA%AF%D9%88%D8%B1%DB%8C%D8%AA%D9%85_%D8%AC%D8%B3%D8%AA%D8%AC%D9%88%DB%8C_%D8%AF%D9%88%D8%AF%D9%88%DB%8C%DB%8C | |
*/ | |
function binarySearch(arr, x, start, end) { | |
if (start > end) return -1; | |
let mid = Math.floor((start + end) / 2); | |
if (arr[mid] === x) return mid; | |
if (arr[mid] > x) return binarySearch(arr, x, start, mid - 1); | |
else return binarySearch(arr, x, mid + 1, end); | |
} | |
/* | |
* Binary Search | |
* find exist item | |
*/ | |
function binarySearch(array, search) { | |
const mid = Math.floor(array.length / 2); | |
if (array[mid] === search) return true; | |
if (array[mid] < search) return binarySearch(array.slice(mid + 1), search); | |
if (array[mid] > search) return binarySearch(array.slice(0, mid), search); | |
return false; | |
} | |
/* | |
* Bubble Sort | |
*/ | |
function bubbleSort(array) { | |
const length = array.length; | |
for (let i = 0; i < length-1; i++){ | |
for (let j = 0; j < length-1; j++){ | |
if (array[j] > array[j + 1]) { | |
const temp = array[j + 1]; | |
array[j + 1] = array[j]; | |
array[j] = temp; | |
} | |
} | |
} | |
return array; | |
} | |
/** | |
* Selection Sort | |
*/ | |
function selectionSort(array) { | |
const lenght = array.length; | |
for (let i = 0; i < lenght; i++) { | |
let minValueIndex = i; | |
for (let j = n + 1; j < lenght; j++) { | |
if (array[j] < array[minValueIndex]) { | |
minValueIndex = j; | |
} | |
} | |
const temp = array[i]; | |
array[i] = array[minValueIndex]; | |
array[minValueIndex] = temp; | |
} | |
return array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment