Mover todos los ceros al final de la array | Set-2 (Usando recorrido simple)

Dada una array de n números. El problema es mover todos los 0 al final de la array manteniendo el orden de los otros elementos. Solo se requiere un recorrido único de la array.
Ejemplos: 
 

Input : arr[]  = {1, 2, 0, 0, 0, 3, 6}
Output : 1 2 3 6 0 0 0

Input: arr[] = {0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9}
Output: 1 9 8 4 2 7 6 9 0 0 0 0 0

Algoritmo: 
 

moveZerosToEnd(arr, n)
    Initialize count = 0
    for i = 0 to n-1
        if (arr[i] != 0) then
            arr[count++]=arr[i]
    for i = count to n-1
        arr[i] = 0

diagrama de flujo

CPP

// C++ implementation to move all zeroes at
// the end of array
#include <iostream>
using namespace std;
 
// function to move all zeroes at
// the end of array
void moveZerosToEnd(int arr[], int n)
{
    // Count of non-zero elements
    int count = 0;
 
    // Traverse the array. If arr[i] is non-zero, then
    // update the value of arr at index count to arr[i]
    for (int i = 0; i < n; i++)
        if (arr[i] != 0)
            arr[count++] = arr[i];
    
    // Update all elements at index >=count with value 0
    for (int i = count; i<n;i++)
        arr[i]=0;
}
 
// function to print the array elements
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver program to test above
int main()
{
    int arr[] = { 0, 1, 9, 8, 4, 0, 0, 2,
                         7, 0, 6, 0, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "Original array: ";
    printArray(arr, n);
 
    moveZerosToEnd(arr, n);
 
    cout << "\nModified array: ";
    printArray(arr, n);
 
    return 0;
}
 
// This code is contributed by Ashutosh Singh

Java

// Java implementation to move
// all zeroes at the end of array
import java.io.*;
 
class GFG {
 
// function to move all zeroes at
// the end of array
static void moveZerosToEnd(int arr[], int n) {
     
    // Count of non-zero elements
    int count = 0;
 
    // Traverse the array. If arr[i] is non-zero, then
    // update the value of arr at index count to arr[i]
    for (int i = 0; i < n; i++)
        if (arr[i] != 0)
            arr[count++] = arr[i];
    
    // Update all elements at index >=count with value 0
    for (int i = count; i<n;i++)
        arr[i]=0;
}
 
// function to print the array elements
static void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
    System.out.print(arr[i] + " ");
}
 
// Driver program to test above
public static void main(String args[]) {
    int arr[] = {0, 1, 9, 8, 4, 0, 0, 2,
                         7, 0, 6, 0, 9};
    int n = arr.length;
 
    System.out.print("Original array: ");
    printArray(arr, n);
 
    moveZerosToEnd(arr, n);
 
    System.out.print("\nModified array: ");
    printArray(arr, n);
}
}
 
// This code is contributed by Ashutosh Singh

Python3

# Python implementation to move all zeroes at
# the end of array
 
# function to move all zeroes at
# the end of array
def moveZerosToEnd (arr, n):
 
    # Count of non-zero elements
    count = 0;
 
 
    # Traverse the array. If arr[i] is non-zero, then
    # update the value of arr at index count to arr[i]
    for i in range(0, n):
        if (arr[i] != 0):
            arr[count] = arr[i]
            count+=1
    
    # Update all elements at index >=count with value 0
    for i in range(count, n):
        arr[i] = 0
 
 
 
# function to print the array elements
def printArray(arr, n):
 
    for i in range(0, n):
        print(arr[i],end=" ")
 
 
# Driver program to test above
arr = [ 0, 1, 9, 8, 4, 0, 0, 2,
    7, 0, 6, 0, 9 ]
n = len(arr)
 
print("Original array:", end=" ")
printArray(arr, n)
 
moveZerosToEnd(arr, n)
 
print("\nModified array: ", end=" ")
printArray(arr, n)
 
# This code is contributed by
# Ashutosh Singh

C#

// C# implementation to move
// all zeroes at the end of array
using System;
 
class GFG {
 
    // function to move all zeroes at
    // the end of array
    static void moveZerosToEnd(int[] arr, int n)
    {
        // Count of non-zero elements
        int count = 0;
 
      // Traverse the array. If arr[i] is non-zero, then
      // update the value of arr at index count to arr[i]
      for (int i = 0; i < n; i++)
        if (arr[i] != 0)
            arr[count++] = arr[i];
    
      // Update all elements at index >=count with value 0
      for (int i = count; i<n;i++)
        arr[i]=0;
     
     }
 
    // function to print the array elements
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver program to test above
    public static void Main()
    {
        int[] arr = { 0, 1, 9, 8, 4, 0, 0, 2,
                    7, 0, 6, 0, 9 };
        int n = arr.Length;
 
        Console.Write("Original array: ");
        printArray(arr, n);
 
        moveZerosToEnd(arr, n);
 
        Console.Write("\nModified array: ");
        printArray(arr, n);
    }
}
 
// This code is contributed by Ashutosh Singh

Javascript

<script>
// JavaScript implementation to move all zeroes at
// the end of array
 
 
// function to move all zeroes at
// the end of array
function moveZerosToEnd(arr, n)
{
    // Count of non-zero elements
    let count = 0;
 
    // Traverse the array. If arr[i] is non-zero, then
    // update the value of arr at index count to arr[i]
    for (let i = 0; i < n; i++)
        if (arr[i] != 0)
        {
                arr[count] = arr[i];
                count = count + 1;
         }
     
    // Update all elements at index >= count with value 0
    for (let i = count; i < n; i++)
        arr[i] = 0
 
}
 
// function to print the array elements
function printArray(arr, n)
{
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}
 
// Driver program to test above
 
    let arr = [ 0, 1, 9, 8, 4, 0, 0, 2,
                        7, 0, 6, 0, 9 ];
    let n = arr.length;
 
    document.write("Original array: ");
    printArray(arr, n);
 
    moveZerosToEnd(arr, n);
 
    document.write("<br>" + "Modified array: ");
    printArray(arr, n);
 
 
//This code is contributed by Ashutosh Singh
</script>
Producción

Original array: 0 1 9 8 4 0 0 2 7 0 6 0 9 
Modified array: 1 9 8 4 2 7 6 9 0 0 0 0 0 

Complejidad temporal: O(n). 
Espacio Auxiliar: O(1).
 

Publicación traducida automáticamente

Artículo escrito por ayushjauhari14 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *