working link
//quicksort implementation in typescript
//full detail please check https://www.youtube.com/watch?v=COk73cpQbFQ
class Quicksort
{
//pass arry
static sort( arry:Array<number>)
{
//get start index
let start=0;
//get end index which is one less tahn total length
let end=arry.length-1;
//pass arry with start and end index to the function quickSort
this.quickSort(arry,start,end);
}
static quickSort(arry:Array<number>,start:number,end:number)
{
//do sorting using divide and conquer
if(start<end)
{
//get a pivot index
let pindex=this.getPivotIndex(arry,start,end);
this.quickSort(arry,start,pindex-1);
this.quickSort(arry,pindex+1,end);
}
}
//swap element
static swap(arry:Array<number>,start:number,index:number)
{
let temp=arry[start];
arry[start]=arry[index];
arry[index]=temp;
}
static getPivotIndex(arry:Array<number>,start:number,end:number):number
{
let pivot=arry[end];
let pindex=start;
for(let i=start;i<end;i++)
{
if(arry[i]<=pivot)
{
this.swap(arry,i,pindex)
pindex+=1;
}
}
this.swap(arry,pindex,end);
return pindex;
}
}
var arry=[];
for(var i=0;i<25;i++)
{
arry.push(Math.round(Math.random()*100));
}
console.time()
Quicksort.sort(arry);
console.log(arry);
console.timeEnd()
Comments
Post a Comment