forked from Asiatik/codezilla
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request Asiatik#404 from ooHAoo/issue1
Added Linear Search and Binary Search in Javascript
- Loading branch information
Showing
2 changed files
with
31 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
/** Binary search algorithm in Javascript **/ | ||
/** Follows the README.md **/ | ||
|
||
function binarySearch(array, target) { | ||
let leftIndex = 0; | ||
let rightIndex = array.length - 1; | ||
let middleIndex; | ||
|
||
while (leftIndex <= rightIndex) { | ||
middleIndex = leftIndex + Math.floor((rightIndex - leftIndex) / 2); | ||
if (array[middleIndex] === target) { | ||
return middleIndex; | ||
} | ||
if (arr[middleIndex] < target) { | ||
leftIndex = middleIndex + 1; | ||
} else { | ||
rightIndex = middleIndex - 1; | ||
} | ||
} | ||
return -1; | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
/** Binary search algorithm in Javascript **/ | ||
|
||
function linearSearch(array, item) { | ||
for (let i = 0; i < array.length; i++) { | ||
if(array[i] === item) { | ||
return i; | ||
} | ||
} | ||
return -1; | ||
} |