Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created October 2, 2016 12:58
Show Gist options
  • Save vlad-bezden/815083d965c682ce4032449c205fc8fa to your computer and use it in GitHub Desktop.
Save vlad-bezden/815083d965c682ce4032449c205fc8fa to your computer and use it in GitHub Desktop.
Binary Search
<h1 id="qunit-header">QUnit Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
'use strict'
/**
* Binary Search implementation example
*
* @param {number[]} data - sorted array of numbers
* @param {number} item - value that has to be found
* @return {number} - index of the found item in an array, otherwise -1
*/
function binarySearch(data, item) {
let lowIndex = 0
let highIndex = data.length - 1
while (lowIndex <= highIndex) {
let mid = Math.trunc((lowIndex + highIndex) / 2)
let guess = data[mid]
if (guess === item) {
return mid
} else if (guess < item) {
lowIndex = mid + 1
} else if (guess > item) {
highIndex = mid - 1
}
}
return -1
}
// Teststs
const data = [0, 1, 2, 5, 7, 11, 20, 22, 45, 75, 100]
QUnit.test("binarySearch tests", (assert) => {
data.forEach((x, i) => {
assert.equal(binarySearch(data, x), i)
})
assert.equal(binarySearch(data, 99), -1)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/qunit/2.0.1/qunit.min.js"></script>
body {
background-color: #222;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/qunit/2.0.1/qunit.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment