Skip to content

Instantly share code, notes, and snippets.

@Walkeryr
Last active January 27, 2018 11:00
Show Gist options
  • Save Walkeryr/6b4a6e3bbd2595db248e30024b7a06c2 to your computer and use it in GitHub Desktop.
Save Walkeryr/6b4a6e3bbd2595db248e30024b7a06c2 to your computer and use it in GitHub Desktop.
Binary search visualization
license: MIT
height: 400
border: no

Binary search visualization.

function binarySearch(list, item) {
let low = 0;
let high = list.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
const guess = list[mid];
if (guess === item) {
return mid;
} else if (guess > item) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Binary search visualization</title>
<style>
.viz {
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 800px;
height: 400px;
}
.bar {
stroke: #fff;
stroke-width: 1;
rx: 1;
ry: 2;
}
</style>
</head>
<body>
<svg>
<linearGradient id="Gradient2" x1="0" x2="1" y1="0" y2="0">
<stop offset="0%" stop-color="#42A5F5" />
<stop offset="100%" stop-color="rgba(64, 84, 178, 0.3)" />
</linearGradient>
</svg>
<div class="viz"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="algorithm.js"></script>
<script src="visualization.js"></script>
</body>
</html>
const MARGINS = { left: 20, right: 20, top: 20, bottom: 20 };
const VIEW_WIDTH = 800;
const VIEW_HEIGHT = 400;
const MAX_NUMBER = 1000;
const ITEMS_NUMBER = 95;
// Generate an array of random values
let list = Array.from(Array(ITEMS_NUMBER), (item, index) =>
Math.floor(Math.random() * MAX_NUMBER)
);
// Sort an array for algorithm
list.sort((a, b) => a - b);
const graphWidth = VIEW_WIDTH - MARGINS.left - MARGINS.right;
const graphHeight = VIEW_HEIGHT - MARGINS.top - MARGINS.bottom;
const gap = 0;
const barWidth = (graphWidth - gap * (list.length - 1)) / list.length;
const linearScale = d3
.scaleLinear()
.domain([0, MAX_NUMBER])
.range([0, graphHeight]);
const opacityScale = d3
.scaleLinear()
.domain([0, MAX_NUMBER])
.range([0.3, 1]);
const svg = d3
.select(".viz")
.append("svg")
.attr("width", VIEW_WIDTH)
.attr("height", VIEW_HEIGHT);
svg
.selectAll("rect")
.data(list)
.enter()
.append("rect")
.attr("width", function(d, i) {
return barWidth;
})
.attr("height", function(d, i) {
return linearScale(d);
})
.attr("x", function(d, i) {
return i * barWidth + i * gap + MARGINS.left;
})
.attr("y", function(d, i) {
return graphHeight - linearScale(d);
})
.attr("fill", function(d, i) {
return `rgba(64, 84, 178, ${opacityScale(d)})`;
})
.classed("bar", true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment