Bubble Sort
by jessekinsman
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react-dom.js"></script>
<div id='target'>no snapshots</div>
CSS
td {
color: white;
padding: 5px;
text-align: center;
}
table {
margin-bottom: 10px;
}
Babel + JSX
let bubbleSort = (nums) => {
let swap = true;
while (swap === true) {
swap = false;
for (var i = 0; i < nums.length; i++) {
snapshot(nums);
if (i+1 < nums.length) {
if (nums[i] > nums[i+1]) {
var tmp = nums[i];
nums[i] = nums[i+1];
nums[i+1] = tmp;
swap = true;
}
}
}
}
snapshot(nums);
return nums
}
// The following is just the visualization of the snapshot
const snapshots = [];
const snapshot = array => snapshots.push(Array.from(array));
const range = length => Array.apply(null, {length}).map(Number.call, Number);
const done = () => {
let reduced = snapshots.reduce( (accumulator, current) => {
let shouldAdd = false;
if (accumulator.length) {
let prev = accumulator[accumulator.length-1];
for (let i = 0 ; i < current.length; i++) {
if (current[i] !== prev[i]) {
shouldAdd = true;
break;
}
}
}
else {
shouldAdd = true;
}
if (shouldAdd) {
accumulator.push(current)
}
return accumulator;
}, []);
ReactDOM.render(
<App snapshots={reduced} count={snapshots.length} />,
document.getElementById('target')
);
return snapshots.length;
}
class App extends React.Component {
render() {
const max = Math.max.apply(Math,this.props.snapshots[0]);
const min = Math.min.apply(Math,this.props.snapshots[0]);
return (
<div>
<h1>Comparisons: {this.props.count}</h1>
<table>
<tbody>
{this.props.snapshots.map( (snapshot, index) => <Snapshot max={max} min={min} key={index} data={snapshot} /> )}
</tbody>
</table>
</div>
);
}
}
class Snapshot extends React.Component {
getColor(input) {
const max = this.props.max - this.props.min;
const value = input - this.props.min;
const spectrum = value/max;
const red = (spectrum < .5) ? Math.floor(Math.abs(spectrum - .5) * 2 * 255) : 0;
const...