So I decided to make a more efficient solution to a Google interview question where they ask you to either find the lowest or second lowest value in an array without using the max or min methods. I believe it is more efficient because you can use my method to find any nth lowest value in the array so it solves for all cases.
Please let me know if there is anything I can do to improve this solution or if there is anything I am missing:
/*Algorithm:
-first sort the array from ascending order
-Then iterate over the array with a loop
-if(array[i + nth lowest input you want])
-return the output
function nThOrderStatistic(array, number):
-if you want to find the lowest number sub in 0 for number
-for every nth lowest number you would sub in n - 1 for the number */
function nThOrderStatistic(array, number) {
array.sort(function(a,b){return a -b});
for(i = 0; i < array.length; i++)
{
if(array[i + number] < array[i + (number + 1)])
{
return array[i + number];
}
}
}
nThOrderStatistic([6,7,43,2,95], 2);
//sample output for 3rd lowest value is: 7 //