TLE in "Stacks": Problem Code: STACKS

var arr = '';
process.stdin.on('data',function(chunk){
   arr += chunk; 
});
process.stdin.on('end',function(){
   arr = arr.split('\n');
   let t = parseInt(arr[0]),i=1,n,radii,line=1,len,j,k,stack;
   while(i<=t){
        n = parseInt(arr[line++]);
        radii = arr[line++].split(' ');
        len = radii.length;
        stack = [];
        for(j=0;j<len;j++){
            if(stack.length === 0) stack.push(parseInt(radii[j]));
            else{
                if(parseInt(radii[j]) > stack[stack.length-1]) stack.push(parseInt(radii[j]));
                else{
                    for(k=0;k<stack.length;k++){
                        if(stack[k]>parseInt(radii[j])){
                            stack[k] = parseInt(radii[j]);   
                            break;
                        }
                    }
                }
            }
        }
        console.log(stack.length+" "+stack.join(' '));
        i++;   
    }
});

I wrote the program of “Stack” in node.js but the output is coming “time limit exceeded”. The same program when I am writing in C then it is getting executed successfully. Where the time complexity in both the case is O(n3). Anyone have any idea to do it in javascript?

Here we go, i did it in Javascript. I change my logic and implemented binary search for getting the index to put the disk.
All i want to know how come the time complexity reduces for binary search. If you notice the time complexity for my above solution is O(n3) and for binary search it is O(n3logn). So where is the reduction of the time complexity?
Below is my AC solution with binary search:-

var arr = '',stack;
process.stdin.on('data',function(chunk){
   arr += chunk; 
});
process.stdin.on('end',function(){
   arr = arr.split('\n');
   let t = parseInt(arr[0]),i=1,n,radii,line=1,len,j,k;
   while(i<=t){
        n = parseInt(arr[line++]);
        radii = arr[line++].split(' ');
        len = radii.length;
        stack = [];
        for(j=0;j<len;j++){
            if(stack.length === 0) stack.push(parseInt(radii[j]));
            else{
                if(parseInt(radii[j]) >= stack[stack.length-1]) stack.push(parseInt(radii[j]));
                else{
                    let index = binarySearch(0,stack.length-1,parseInt(radii[j]));
                    if(index == -1) stack[0] = parseInt(radii[j]);
                    else stack[index] = parseInt(radii[j]);
                }
            }
        }
        console.log(stack.length+" "+stack.join(' '));
        i++;   
    }
});

function binarySearch(l,h,key){
    while(l<h){
        let mid = Math.floor((l+h)/2);
        if(stack[mid]<=key && stack[mid+1]>key) return mid+1;   
        else if(stack[mid]>key) h = mid;
        else l = mid+1;
    }
    return -1;
}