Skip to content

Instantly share code, notes, and snippets.

@debruine
Created May 9, 2022 09:33
Show Gist options
  • Save debruine/e6988132be5cd01969936f957a9ca758 to your computer and use it in GitHub Desktop.
Save debruine/e6988132be5cd01969936f957a9ca758 to your computer and use it in GitHub Desktop.
Visualise a sorting algorithm
library(ggplot2)
library(dplyr)
# make starting vector
A = LETTERS[5:1]
# pre-allocate matrix to store steps
n = length(A)
steps <- matrix(nrow = (n*n)+1,
ncol = 2 + n)
steps[1, ] = c(0, 0, A)
# iterate
for (i in 1:n) {
for (j in 1:n) {
if (A[i] < A[j]){
Ai = A[i]; Aj = A[j]
A[i] = Aj; A[j] = Ai
}
steps[(i-1)*n + j+1,] = c(i, j, A)
}
}
# get matrix to long df
steps_df <- as.data.frame(steps)
names(steps_df) = c("i", "j", paste0("pos_", 1:n))
steps_df$step = 1:nrow(steps_df)-1
steps_df = tidyr::pivot_longer(steps_df,
cols = starts_with("pos_"),
names_to = "position",
names_prefix = "pos_",
values_to = "value",
names_transform = list(position = as.integer))
# bump plot
ggplot(data = steps_df,
mapping = aes(x = step,
y = position,
label = value,
colour = value)) +
ggbump::geom_bump(size = 4, alpha = 0.5) +
geom_text(data = filter(steps_df, step == max(step)),
color = "black",
hjust = 0, nudge_x = 0.2) +
geom_text(data = filter(steps_df, step == min(step)),
color = "black",
hjust = 1, nudge_x = -0.2) +
scale_y_reverse(breaks = 1:n,
expand = expansion(.2)) +
theme(legend.position = "none")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment