Skip to content

Commit

Permalink
searching algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
karan1205 committed Mar 5, 2022
1 parent 2fec3fb commit 35e8003
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
16 changes: 16 additions & 0 deletions DSA/searching-algorithms/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Searching Algorithms

* Searching Algorithms are designed to check for an element or retrieve an element from any data structure where it is stored.

## [Linear Search](linear-search.js)
* The list or array is traversed sequentially and every element is checked.

## [Binary Search](binary-search.js)
* Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half.
* The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).

## The basic steps to perform Binary Search are:
* Begin with an interval covering the whole array.
* If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
* Otherwise, narrow it to the upper half.
* Repeatedly check until the value is found or the interval is empty.
27 changes: 27 additions & 0 deletions DSA/searching-algorithms/binary-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Given a sorted array if integers, write a function called search, that accepts a value and returns the index where the value passed to the function is located.
* If the value is not found, return -1;
*/

function search(arr, n) {
let left = 0;
let right = arr.length - 1;

while(left <= right) {
const mid = Math.floor((left + right) / 2);
if(arr[mid] === n) {
return mid;
}
if(arr[mid] < n) {
left = mid+1;
} else {
right = mid - 1;
}
}
return -1;
}

// const result = search([1,2,3,4,5,6], 4); // 3
// const result = search([1,2,3,4,5,6], 6); // 5
// const result = search([1,2,3,4,5,6], 11); // -1
// console.log(result);
17 changes: 17 additions & 0 deletions DSA/searching-algorithms/linear-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Linear Search
* Given an array arr[] of n elements, write a function to search a given element val in arr[].
*/

function linearSearch(arr, val) {
for(let i =0; i<arr.length; i++) {
if(arr[i] === val) {
return i;
}
}
return -1;
}

// const result = linearSearch([1,2,4,7,3], 7);
// const result = linearSearch([1,2,4,7,3], 5);
// console.log(result);

0 comments on commit 35e8003

Please sign in to comment.