diff --git a/algorithm/sorts.js b/algorithm/sorts.js new file mode 100644 index 00000000..50c5219e --- /dev/null +++ b/algorithm/sorts.js @@ -0,0 +1,101 @@ +function selectionSort(arr){ + const result = arr; + const n = arr.length; + for(let i=0;iresult[j]){ + minIndex = j; + } + } + if(minIndex !== i){ + let temp = result[i]; + result[i] = result[minIndex]; + result[minIndex] = temp; + } + } + return result; +} +function insertionSort(arr){ + for(let i=1;i=0 && arr[j]>current;j--){ + arr[j+1] = arr[j]; + } + arr[j+1]=current; + } +} +function mergeSort(arr){ + if(arr.length<=1){ + return arr; + } + + const mid = Math.floor(arr.length/2); + const left = arr.slice(0,mid); + const right= arr.slice(mid); + + const sortedLeft = mergeSort(left); + const sortedRight = mergeSort(right); + + return merge(sortedLeft,sortedRight); +} + +function merge(left,right){ + const result = []; + let i=0; + let j=0; + + while(i