In-place Algorithm to Move Zeros to End of List in JavaScript

JavascriptWeb DevelopmentFront End Technology

Suppose we are given an array of integers, lets say arr. We are required to write a function that puts all the zeros to the back of the array by modifying the list in-place.

The function should do this in such a way that the relative ordering of other elements should stay the same.

For example −

If the input array is −

const arr = [0, 11, 0, 22, 67];

Then the array should be modified to −

const output = [11, 22, 67, 0, 0];

Example

Following is the code −

const arr = [0, 11, 0, 22, 67];
const moveZeroToEnd = (arr = []) => {
   const swap = (array, ind1, ind2) => {
      const temp = array[ind1];
      array[ind1] = array[ind2];
      array[ind2] = temp;
   };
   let j = 0;
   for (let i = 0; i < arr.length; ++ i) {
      if (arr[i] !== 0) {
         swap(arr, i, j++);
      }
   }
   while (j < arr.length) {
      arr[j++] = 0;
   };
};
moveZeroToEnd(arr);
console.log(arr);

Output

Following is the console output −

[11, 22, 67, 0, 0]
raja
Published on 23-Jan-2021 06:39:38
Advertisements