working example
https://stackblitz.com/edit/typescript-lchwhz
Please remember this is not the best way to implement merge short in javascript but its a classic way using without any inbuilt API method.
more detail about merge sort is=>
https://www.youtube.com/watch?v=TzeBrDU-JaY
https://stackblitz.com/edit/typescript-lchwhz
Please remember this is not the best way to implement merge short in javascript but its a classic way using without any inbuilt API method.
more detail about merge sort is=>
https://www.youtube.com/watch?v=TzeBrDU-JaY
//merge sort in typescript using classic way you can easliy reduce this method to sorter one depends on your requirement
class sortAlgo
{
static sort(myArray:Array<number>)
{
//left bound
let left=0;
//right bound just one less than total array length
let right=myArray.length-1;
//divide array in to small part
this.divideArray(myArray,left,right);
}
static divideArray(myArray:Array<number>,left:number,right:number)
{
//recursive call util left < right
if(left<right)
{
//find mid to preventing stack overflow right-1
let mid=Math.round(left+right-1/2);
//divide left part
this.divideArray(myArray,left,mid-1);
//divide right part
this.divideArray(myArray,mid+1,right);
//merge both part
this.mergeArray(myArray,left,right,mid);
}
}
static mergeArray(myArray:Array<number>,left:number,right:number,mid:number)
{
//create two array
let leftArray=[];
let rightArray=[];
//fill left and right array
this.fillArray(left,mid,leftArray,myArray);
this.fillArray(mid,right+1,rightArray,myArray);
//swap/exchange values between left and right array in shorted manner
let i=0,j=0,k=0;
while(i<leftArray.length && j<rightArray.length)
{
if(leftArray[i]<rightArray[j])
{
myArray[k]=leftArray[i];
i++;
}
else
{
myArray[k]=rightArray[j];
j++;
}
k++;
}
while(i<leftArray.length)
{
myArray[k]=leftArray[i];
i++;
k++;
}
while(j<rightArray.length)
{
myArray[k]=rightArray[j];
j++;
k++;
}
}
static fillArray(from:number,to:number,toArray:Array<number>,fromArray:Array<number>)
{
for(let i=from;i<to;i++)
{
toArray.push(fromArray[i]);
}
}
}
var myArray=[];
for(let i=0;i<20;i++)
{
myArray.push(5+Math.round(Math.random()*25));
}
console.log(myArray);
sortAlgo.sort(myArray);
console.log(myArray);
Comments
Post a Comment