Put Numbers in Ascending Order


Posted by Christy on 2022-04-23

Description: Write a function named sort that accepts an array and return the array in ascending order

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

Thought:

Find the minimum value first and push it into a new array and delete the minimum value in the original array and so on.

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 sort(arr) {
  let newArr = [];
  let length = arr.length;
  for (let i = 0; i < length; i++) {
    let index = findMin(arr);
    newArr.push(arr[index]);
    arr.splice(index, 1);
  }
  return newArr;
}

console.log(sort([6, 8, 3, 2])); // [2, 3, 6, 8]
console.log(sort([1, 2, 7, 5])); // [1, 2, 5, 7]

Reflection:

The key is to get the index and either delete or push it in an array.










Related Posts

20210413 wk1 筆記

20210413 wk1 筆記

GIT Github

GIT Github

AI輔導室|製作相扣的紙花圈

AI輔導室|製作相扣的紙花圈


Comments