Java 将所有的零移动到数组的末尾

Java 将所有的零移动到数组的末尾

在Java中,数组是一个对象。它是一个非原始数据类型,存储相似数据类型的值。

根据问题的陈述,我们需要将所有的零移动到数组的末尾,即如果一个数组中包含n个零,则所有的n个零都将被推到数组的末尾。

让我们来探讨一下这篇文章,看看如何使用Java编程语言实现这个功能。

给你看一些示例

示例1

假设原数组是{128, 0, 99, 67, 50, 0, 29, 7, 0}

将所有的零移动到数组的末尾后,结果将是:

将所有的零移动到数组的末尾后,数组的元素为:

128 99 67 50 29 7 0 0 0

示例2

假设原数组是{23, 9, 6, 4, 0, 0, 21, 7, 0, 6, 0, 9}

将所有的零移动到数组的末尾后,结果将是:

将所有的零移动到数组的末尾后,数组的元素为:

23 9 6 4 21 7 6 9 0 0 0 0

示例3

假设原数组是{3, 9, 5, 1, 0, 0, 11, 6, 0, 9}

将所有的零移动到数组的末尾后,结果将是:

将所有的零移动到数组的末尾后,数组的元素为:

3 9 5 1 11 6 9 0 0 0

步骤

步骤1(使用排序)

  • 步骤1 - 声明并初始化一个整数数组。

  • 步骤2 - 实现多种方法的逻辑。

  • 步骤3 - 按降序对数组进行排序,零将位于最后位置。

  • 步骤4 - 打印数组的元素。

步骤2(通过手动迭代和替换)

  • 步骤1 - 声明并初始化一个整数数组。

  • 步骤2 - 实现多种解决方案的逻辑。

  • 步骤3 - 将所有非零元素推到数组的左侧,零元素保留在最后。

  • 步骤4 - 打印数组的元素。

语法

要获得数组的长度(即数组中的元素数),有一个内置属性称为length。

下面是它的语法 –

array.length

其中,’array’指的是数组的引用。

多种方法

我们提供了不同的方法来解决问题。

  • 通过排序

  • 通过手动迭代和替换

让我们逐个查看程序及其输出。

方法1:通过排序

在这种方法中,程序将初始化数组元素。然后根据算法按降序对数组进行排序,因此零将会出现在最后位置。

示例

import java.util.*;
public class Main {
   public static void main(String[] args){

      //Declare and initialize the array elements
      int array[] = {128, 0, 99, 67, 50, 0, 29, 7, 0};

      //getting length of an array
      int n = array.length;

      //calling user defined function
      func(array, n);
   }

   //user defined method
   public static void func(int array[], int n) {

      //sorting the array elements
      Arrays.sort(array);
      System.out.println("Elements of array after moving all the zeros to the end of array: ");

      //prints array using the for loop
      for (int i = n-1; i >= 0; i--) {
         System.out.print(array[i] + " ");
      }
   }
}

输出

Elements of array after moving all the zeros to the end of array: 
128 99 67 50 29 7 0 0 0

方法2:手动迭代和替换

在这种方法中,程序将会初始化数组元素。然后根据算法,将所有非零元素推到数组的左边,而零元素保留在最后。

示例

import java.io.*;
public class Main {
   public static void main (String[] args){

      //Declare and initialize the array elements
      int arr[] = {3, 9, 5, 1, 0, 0, 11, 6, 0, 9};

      //getting length of an array
      int n = arr.length;

      //calling user defined method
      func(arr, n);
   }

   //user defined method
   static void func(int arr[], int n) {
      // Count of non-zero elements
      int count = 0;

      //shifting non zero element to the left of the loop
      for (int i = 0; i < n; i++)
      if (arr[i] != 0)
      arr[count++] = arr[i];

      //adding the zeros to the end
      while (count < n)
      arr[count++] = 0;

      //printing the result
      System.out.println("Elements of array after moving all the zeros to the end of array: ");
      for (int i = 0; i < n; i++)
      System.out.print(arr[i] + " ");
   }
}

输出

Elements of array after moving all the zeros to the end of array: 
3 9 5 1 11 6 9 0 0 0

在本文中,我们探讨了如何使用Java编程语言将所有的零移动到数组的末尾。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程