Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- void swap(int * array, int & left, const int right)
- {
- while (array[left] != 0)
- left++;
- array[left] = array[right];
- array[right] = 0;
- }
- int moveZerosToTheLeft(int * array, const size_t len)
- {
- int left = 0;
- 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
- {
- if (array[i] != 0) //Move this zero to the left side
- swap(array, left, i); //by swapping it with the leftmost zero
- }
- return left;
- }
- int main(void)
- {
- int array[] = { 0, 1, 0, 2, 0, 0, 3, 4, 1, -23, 441, 0, -11, 2, 12, 1, 8, 0, 0 };
- int len = sizeof(array) / sizeof(array[0]);
- moveZerosToTheLeft(array, len);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement