I made a very simple canvas app for visualising some basic sorting algorithms by GopherJS
package sort
import "time"
type BubbleSort struct {
}
func (s *BubbleSort) Sort(nums []int, id string) {
obj := createCanvas(id, len(nums))
draw(nums, 0, 0, obj)
for i := 0; i < len(nums); i++ {
for j := 0; j < len(nums)-1; j++ {
if nums[j] > nums[j+1] {
nums[j], nums[j+1] = nums[j+1], nums[j]
}
draw(nums, i, j, obj)
time.Sleep(100 * time.Millisecond)
}
}
}
type BubbleSortSwapped struct {
}
func (s *BubbleSortSwapped) Sort(nums []int, id string) {
obj := createCanvas(id, len(nums))
draw(nums, 0, 0, obj)
for i := 0; i < len(nums); i++ {
swapped := false
for j := 0; j < len(nums)-1; j++ {
if nums[j] > nums[j+1] {
nums[j], nums[j+1] = nums[j+1], nums[j]
swapped = true
}
draw(nums, i, j, obj)
time.Sleep(100 * time.Millisecond)
}
if !swapped {
break
}
}
}
Then I just loaded it in a Vue Component. Hacky.. But works now.
<ACanvasV1 id="bubble"/>
<ACanvasV1 id="bubble_swapped"/>
package sort
import "time"
type SelectionSort struct {
}
func (s *SelectionSort) Sort(nums []int, id string) {
obj := createCanvas(id, len(nums))
draw(nums, 0, 0, obj)
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if nums[i] > nums[j] {
nums[i], nums[j] = nums[j], nums[i]
}
draw(nums, i, j, obj)
time.Sleep(100 * time.Millisecond)
}
}
}
Improve the visualizing part to make the algorithm code clean and the animation better. Considering using svg.js