2

Having this array:

const myArry = [1, 543, 0, 232, 1, 45654, -5, 0, 7, 4, 0, 43, 77, 0, 77, 0]

It must be sorted in ascending order and place all 0s at the end, so the output should be:

[-5, 1, 1, 4, 7, 43, 77, 77, 232, 543, 45654, 0, 0, 0, 0, 0]

For sorting it's straightforward:

function sorting(arr) {

  for(let i = 0; i< arr.length; i++) {
    for (let j = 0; j < arr.length - i -1; j++) {
      if(arr[j+1] < arr[j]) {
        [arr[j+1], arr[j]]=[arr[j], arr[j+1]];
      }
    }
  }

  return arr;
}

But for moving those 0s I cannot find a solution to do it without native functions like push:

function moveZeros(arr) {
  let newArray = [];
  let counter = 0;
  for (let i = 0; i < arr.length; i++) {
    if(arr[i] !== 0) {
      newArray.push(arr[i]);
    }
      else { counter++; }
    }
  for (let j = 0; j < counter; j++) {
    newArray.push(0);
  }
  return newArray;
}

Is there a way to do this? Also, if combining both methods into one

2 Answers 2

3

When sorting numbers, to move all zeroes to the end, you have to give it more weight than any other number. Here, I "edge-cased" zero to always swap such that it moves to the end.

const myArry = [1, 543, 0, 232, 1, 45654, -5, 0, 7, 4, 0, 43, 77, 0, 77, 0]

function sorting(arr) {

  for(let i = 0; i< arr.length; i++) {
    for (let j = 0; j < arr.length - i -1; j++) {
      if(arr[j+1] < arr[j] && arr[j+1] != 0 || arr[j] == 0) {
        [arr[j+1], arr[j]]=[arr[j], arr[j+1]];
      }
    }
  }

  return arr;
}

console.log('' + sorting(myArry))

Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with the sort function. It s much readable.

myArry.sort((a, b) => { 
  if(b === 0) return -Infinity; 
  if(a === 0) return Infinity; 
  return a -b 
})

1 Comment

I know but sort is a built-in function and in this scenario it should be avoided

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.