Advertisement
Guest User

One-pass solution

a guest
Nov 21st, 2014
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. #include "stdafx.h"
  2.  
  3. void swap(int * array, int & left, const int right)
  4. {
  5.     while (array[left] != 0)
  6.         left++;
  7.     array[left] = array[right];
  8.     array[right] = 0;
  9. }
  10.  
  11. int moveZerosToTheLeft(int * array, const size_t len)
  12. {
  13.     int left = 0;
  14.     for (int i = len - 1; i > left; i--) //now we start from the right until we reach the position of the last non-zero element
  15.     {
  16.         if (array[i] != 0) //Move this zero to the left side
  17.             swap(array, left, i); //by swapping it with the leftmost zero
  18.     }
  19.     return left;
  20. }
  21.  
  22. int main(void)
  23. {
  24.     int array[] = { 0, 1, 0, 2, 0, 0, 3, 4, 1, -23, 441, 0, -11, 2, 12, 1, 8, 0, 0 };
  25.     int len = sizeof(array) / sizeof(array[0]);
  26.     moveZerosToTheLeft(array, len);
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement