Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move the zeros from an array at the end without using native functions

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading