We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Sort, then pick the midpoint seemed the easiest. But sort is O(n log n), right? If so, can we use a better sort and get to O(n)?
So,if we look at a sorted array and median is midpoint, then we can assume the NthSmallest integer where n is the midpoint is what we are looking for. Then we only have to adjust our sort until then.
Typescript:
functionfindNthSmallest(arr:number[],n:number):number{letleft:number=0;letright:number=arr.length-1;while(left<=right){constpivotNdx=partition(arr,left,right);if(pivotNdx===n){returnarr[pivotNdx];// we know what's left of index is lower than everything else}elseif(pivotNdx<n){left=pivotNdx+1;// we know what's right of index is larger than everything else}else{right=pivotNdx-1;}}}functionpartition(arr:number[],left:number,right:number):number{constpivot=arr[right];leti=left-1;for(letj=left;j<right;j++){if(arr[j]<=pivot){i++;[arr[i],arr[j]]=[arr[j],arr[i]];}}[arr[i+1],arr[right]]=[arr[right],arr[i+1]];returni+1;}functionfindMedian(arr:number[]):number{// find mid smallest number, use own copy of arrreturnfindNthSmallest([...arr],Math.floor(arr.length/2));}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Find the Median
You are viewing a single comment's thread. Return to all comments →
Sort, then pick the midpoint seemed the easiest. But sort is O(n log n), right? If so, can we use a better sort and get to O(n)? So,if we look at a sorted array and median is midpoint, then we can assume the NthSmallest integer where n is the midpoint is what we are looking for. Then we only have to adjust our sort until then.
Typescript: