Home > Software design >  Move the zeros from an array at the end without using native functions
Move the zeros from an array at the end without using native functions

Time:10-08

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

CodePudding user response:

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))

CodePudding user response:

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 
})
  • Related