Insertion sort
js const insertionSort=(arr)=>{ const len=arr.length; if(len<=0){return arr; } for(let i=1; i<len; ++i){ const cur=arr[i]; let j=i-1; for(; j>=0; --j){ if(arr[j]>cur){ arr[j+1]=arr[j]; }else{break; } } arr[j+1]=cur; // Insert position}}
Bubble sort // Compare adjacent elements
`js const bubbleSort=(arr)=>{ const len=arr.length; for(let i=0; i<len; ++i){ let falg=false; for(let j=0; j<len-i-1; ++j){ if(arr[j]>arr[j+1]){ falg=true; [arr[j+1],arr[j]]=[arr[j],arr[j+1]]; }}
if(! falg){ break; }Copy the code
} return arr; } `