Published
Edited
May 12, 2022
3 stars
Insert cell
Insert cell
function SimpleAndSurprisingSort(A) {
A = A.slice();
const n = A.length;

for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
if (A[i] < A[j]) {
[A[j], A[i]] = [A[i], A[j]]; // swap
}
}
}

return A;
}
Insert cell
SimpleAndSurprisingSort(Array.from({ length: 10 }, Math.random))
Insert cell
Insert cell
(replay, VisualizeSimpleAndSurprisingSort(d3.shuffle(d3.range(18))))
Insert cell
function VisualizeSimpleAndSurprisingSort(A) {
A = A.slice();
const n = A.length;

let steps = A.slice();
const swaps = [];

for (let i = 0; i < n; ++i) {
for (let j = 0; j < n; ++j) {
if (A[i] < A[j]) {
[A[j], A[i]] = [A[i], A[j]];
swaps.push({ i, j });
steps = steps.concat(A.slice());
}
}
}

return Plot.plot({
marks: [
Plot.cell(steps, {
x: (d, g) => g % n,
y: (d, g) => Math.floor(g / n),
fill: steps,
stroke: steps
}),
Plot.arrow(swaps, {
x1: "i",
x2: "j",
y: (d, t) => t
})
],
axis: null,
x: { padding: 0 },
y: { padding: 0 },
color: { scheme: "warm" }
});
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more