Skip to content

Instantly share code, notes, and snippets.

@morajabi
Last active October 17, 2017 14:48
Show Gist options
  • Save morajabi/ed36d8590adae5cdaa8a1f79bdd73466 to your computer and use it in GitHub Desktop.
Save morajabi/ed36d8590adae5cdaa8a1f79bdd73466 to your computer and use it in GitHub Desktop.
Untitled benchmark (https://jsbench.github.io/#ed36d8590adae5cdaa8a1f79bdd73466) #jsbench #jsperf
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Untitled benchmark</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/benchmark/1.0.0/benchmark.min.js"></script>
<script src="./suite.js"></script>
</head>
<body>
<h1>Open the console to view the results</h1>
<h2><code>cmd + alt + j</code> or <code>ctrl + alt + j</code></h2>
</body>
</html>
"use strict";
(function (factory) {
if (typeof Benchmark !== "undefined") {
factory(Benchmark);
} else {
factory(require("benchmark"));
}
})(function (Benchmark) {
var suite = new Benchmark.Suite;
suite.add("shiftedArrSearch([11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9)", function () {
shiftedArrSearch([11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9)
function shiftedArrSearch(shiftArr, num) {
// your code goes here
const pivot = findPivotPoint(shiftArr)
if (pivot === 0 || num < shiftArr[0]) {
return binarySearch(shiftArr, pivot, shiftArr.length - 1, num)
}
return binarySearch(shiftArr, 0, pivot - 1, num)
}
// arr: [9, 12, 17, 2, 4, 5]
// i: 0 1 2 3 4 5
// |
// -P-
function findPivotPoint(arr) {
let begin = 0
let end = arr.length - 1
while (begin <= end) {
const mid = Math.floor(end - begin / 2)
// check if it's the pivot point
if (mid === 0 || arr[mid] < arr[mid - 1]) {
return mid
} else if (arr[mid] > arr[0]) {
begin = mid + 1
} else {
end = mid - 1
}
}
return 0
}
function binarySearch(arr, _begin, _end, num) {
let begin = _begin
let end = _end
while (begin <= end) {
const mid = begin + Math.floor((end - begin) / 2)
if (arr[mid] < num) {
begin = mid + 1
} else if (num < arr[mid]) {
end = mid - 1
} else {
// mid === num
return mid
}
}
return -1
}
});
suite.add("shiftedArrSearch([11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9)", function () {
shiftedArrSearch([11, 12, 13, 14, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9)
function shiftedArrSearch(shiftArr, num) {
return shiftArr.findIndex(n => n === num)
}
});
suite.on("cycle", function (evt) {
console.log(" - " + evt.target);
});
suite.on("complete", function (evt) {
console.log(new Array(30).join("-"));
var results = evt.currentTarget.sort(function (a, b) {
return b.hz - a.hz;
});
results.forEach(function (item) {
console.log((idx + 1) + ". " + item);
});
});
console.log("Untitled benchmark");
console.log(new Array(30).join("-"));
suite.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment