Insertion Sort
This is a ChelseaJS visualization of the Insertion Sort algorithm.
The algorithm is a simple sorting algorithm that works by taking an unsorted array and repeatedly stepping through each element in the array, inserting each element into the correct position in the sorted array.
Time Complexity: O(n2)
Insertion sort is typically used to sort short arrays, but it is also used to sort lists that are already mostly sorted.
Code
elem=document.querySelector(".example-container");
setCanvas(elem);
arr=[];
for(i=0;i<WIDTH/2;i++){
arr.push(random(0,HEIGHT));
}
k=0;
function draw(){
clearCanvas();
key= arr[k];
j=k-1;
while(j>=0 && arr[j]>key){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=key;
[arr[min_idx] , arr[k]] = [arr[k],arr[min_idx]]; //es6 destructuring to swap elements
for(i=0;i<arr.length;i++){
x=mapRange(i,0,arr.length,0,WIDTH);
new line(x,HEIGHT,x,HEIGHT-arr[i],'#695fe6',2);
}
if(k<WIDTH/2-1){
k++;
}
requestAnimationFrame(draw);
}
draw()