From 2f6eece500e57c0b3366fdde2874ffe1560c7373 Mon Sep 17 00:00:00 2001 From: Vinaya S Rao <41911422+vinayassrao@users.noreply.github.com> Date: Tue, 19 Oct 2021 18:57:33 +0530 Subject: [PATCH] chore(CPlusPlus): add move zeros to end program (#563) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- .../Arrays/move-zeros-to-end-of-array.cpp | 64 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 2 + 2 files changed, 66 insertions(+) create mode 100644 algorithms/CPlusPlus/Arrays/move-zeros-to-end-of-array.cpp diff --git a/algorithms/CPlusPlus/Arrays/move-zeros-to-end-of-array.cpp b/algorithms/CPlusPlus/Arrays/move-zeros-to-end-of-array.cpp new file mode 100644 index 00000000..1ebe5186 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/move-zeros-to-end-of-array.cpp @@ -0,0 +1,64 @@ +//Given an array of random numbers, Push all the zero’s of a given array to the end of the array. +//For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. +//The order of all other elements should be same. + +#include +using namespace std; + + +void movetoend(int arr[], int n) +{ + int cnt = 0; + + // Traverse the array. If element encountered is non-zero, + // then replace the element at index cnt + // with this element + for (int i = 0 ; i < n; i++) + if (arr[i] != 0) + arr[cnt++] = arr[i]; + + while (cnt < n) + arr[cnt++] = 0; + + // Now all non-zero elements have been shifted to left + // and all zero to the right to the right + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + +} + + +int main() +{ + int n; + cout << "Enter the size" << endl; + cin >> n; + + int arr[n]; + cout << "Enter the array" << endl; + for (int i = 0; i < n; i++) + { + cin >> arr[i]; + } + + int k; + cout << "Array after moving all zeros to end is :" << endl; + movetoend(arr, n); + return 0; +} + +/* + +Sample Input: + + Enter the size + 4 + Enter the array + 1 0 9 0 + Array after moving all zeros to end is : + 1 9 0 0 + +**Time Complexity: O(n), n is the size of the array +**Space Complexity: O(1) + +*/ \ No newline at end of file diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 437ad529..3ef1eabc 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -20,6 +20,8 @@ - [Segregate 0s and 1s](Arrays/segregate-0-and-1.cpp) - [Search insert position](Arrays/search-insert-position.cpp) - [Matrix Multiplication](Arrays/matrix-multiplication.cpp) +- [Smallest Possible Sum](Arrays/smallest-possible-sum.cpp) +- [Move Zeros to End of The Array](Arrays/move-zeros-to-end-of-array.cpp) - [Kadane's Algorithm](Arrays/Kadane's-Algorithm.cpp) ## Dynamic-Programming