![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to move all the zeros to the end of the array from the given array of integer numbers using C#?
Create a method MoveZeros, traverse through the array and count the number of Zeros in the array. Based on the count size make all the final cells to zero. Return without processing if the array length is null or empty. The final result will be in nums Array. Time complexity is O(N) because we are traversing through the array once.
Time complexity − O(N)
Space complexity − O(1)
Example
public class Arrays{ public void MoveZeros(int[] nums){ if (nums == null || nums.Length == 0){ return; } int count = 0; for (int i = 0; i < nums.Count(); i++){ if (nums[i] != 0){ nums[count] = nums[i]; count++; } } for (int i = count; i < nums.Length; i++){ nums[i] = 0; } } } static void Main(string[] args){ int[] nums = { 0, 1, 0, 3, 12 }; s.MoveZeros(nums); foreach (var item in nums){ Console.WriteLine(item); } }
Output
[1,3,12,0,0]
Advertisements