diff --git a/Algorithms/README.md b/Algorithms/README.md index 14fc2b1..305484d 100644 --- a/Algorithms/README.md +++ b/Algorithms/README.md @@ -15,7 +15,7 @@ | Algorithm | Complexity | Implementations | | --- | --- | --- | -| [Linear Search](#LinearSearch) | O(n) | | +| [Linear Search](#LinearSearch) | O(n) | | | [Binary Search](#BinarySearch) | Theta(logn) | | | [Ternary Search](#TernarySearch) | Theta(logn) | | | [Jump Search](#JumpSearch) | O(sqrt(n)) | | diff --git a/Algorithms/Searching/binarySearch.js b/Algorithms/Searching/binarySearch.js new file mode 100644 index 0000000..6bb924f --- /dev/null +++ b/Algorithms/Searching/binarySearch.js @@ -0,0 +1,40 @@ +/* + * Binary Search implementathon in JavaScript. Theta(log n). + */ + +function binarySearch(elements, start, end, x){ + if (start > end){ + return -1 + } + + let middle = Math.floor((start + end) / 2) + console.log(middle) + if (elements[middle] === x){ + return middle + } + if (x < elements[middle]){ + return binarySearch(elements, start, middle - 1, x) + } else { + return binarySearch(elements, middle + 1, end, x) + } + + return -1 +} + +elements = [1, 3, 4, 5, 12, 16, 43, 39, 99] +x = 12 + +left = 0 +right = elements.length + +position = binarySearch(elements, left, right, x) + +console.log("The elemens are: ", elements) +console.log("The element to find is ", x) + +if (position === -1){ + console.log("The element has not been found") +} else { + console.log("The element has been found at position ", position + 1) +} + diff --git a/Algorithms/Searching/linearSearch.js b/Algorithms/Searching/linearSearch.js new file mode 100644 index 0000000..61ae580 --- /dev/null +++ b/Algorithms/Searching/linearSearch.js @@ -0,0 +1,27 @@ +/* Linear Search implementation in JavaScript + * O(n) + */ + +function LinearSearch(elements, x){ + // Linear Search performed on elements to found x + for (var i=0; i < elements.length; i++){ + if (elements[i] === x){ + return i; + } + } + return -1 +} + +let elements = [3, 1, 2, 4, 6, 7, 8, 49, 33, 192] +let x = 4; // element to be found + + +console.log("The elemtents are ", elements) +console.log("The element to be found is: ", x) + +let position = LinearSearch(elements, x) +if (position === -1){ + console.log("The elements has not been found") +} else{ + console.log("The element has been found at position ", position + 1) +} diff --git a/README.md b/README.md index 6d87e7f..f15dce4 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,12 @@ g++ script.cpp -o compiled/script * : +You have to have node installed. + +``` +node script.js +``` + * : ***