Find the nth smallest value


Posted by Christy on 2022-04-23

Description: Write a function named findNthMin that accepts an array and a number n. Find the nth smallest value

Note: Don’t use built-in function sort() and the numbers in the array will not repeat.

Answer 1:

Find minimum value first and delete the minimum value and find minimum value again.

If I would like to find the second smallest value, I will delete the value once, which means it needs to delete the value n - 1 times.

function findMin(arr) {
  let min = arr[0];
  let minIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (min > arr[i]) {
      min = arr[i];
      minIndex = i;
    }
  }
  return minIndex;
}

function findNthMin(arr, nth) {
  for (let i = 1; i <= nth - 1; i++) {
    let minIndex = findMin(arr);
    arr.splice(minIndex, 1);
  }
  let realMinIndex = findMin(arr);
  return arr[realMinIndex];
}
console.log(findNthMin([1, 2, 3], 2));

Answer 2:

function findMin(arr) {
  let min = arr[0];
  let minIndex = 0;
  for (let i = 1; i < arr.length; i++) {
    if (min > arr[i]) {
      min = arr[i];
      minIndex = i;
    }
  }
  return minIndex;
}

function findNthMin(arr, nth) {
  for (let i = 1; i <= nth - 1; i++) {
    let minIndex = findMin(arr);
    arr = arr.filter((item, index) => {
      return index !== minIndex;
    });
  }
  let realMinIndex = findMin(arr);
  return arr[realMinIndex];
}
console.log(findNthMin([1, 2, 3], 2));









Related Posts

Radar Chart - chart.js 的設定

Radar Chart - chart.js 的設定

W19_產品開發流程_學習筆記

W19_產品開發流程_學習筆記

[Week4] JS 實作串接 API(二)

[Week4] JS 實作串接 API(二)


Comments