By Sujoy Datta
An algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. This is a stable technique.
Example:
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0}; Output : arr[] = {1, 2, 4, 3, 5, 0, 0}; Input : arr[] = {1, 2, 0, 0, 0, 3, 6}; Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
Minimal code for advanced programmers:
def move_zeros(arr):
non_zero = [x for x in arr if x is False or x != 0]
return non_zero + [0] * (len(arr) - len(non_zero))
Project Description:
For various data analysis techniques we need to maintain the consistency and strcuture of the data element. The folowing code module attached below presents the safest and easiest technique for a beginner programmer to move the zeroes at the end of an array, without disturbing the stability of the array and preserving the original order of the elements.
In terms of time complexity and auxillary space the program uses O(n). Create an array that is the same size as the initial array you need to remove 0s from. Iterate over the original array and add each element to the new array provided it is not 0. When you encounter a 0, count it. Now, when you've reached the end of the first array, simply add the counted number of 0s to the end of the array.
Submitted by Sujoy Datta (sujoydatta)
Download packets of source code on Coders Packet
Comments