如何将数组中的所有零移动到最后? (JAVA) [英] How do I move all the zeros in an array to the end? (Java)

查看:170
本文介绍了如何将数组中的所有零移动到最后? (JAVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我必须从用户那里获得数组和数组元素的大小并打印输出,以便将数组元素的零移动到最后。



但我得到的只是零。



示例:

4(数组大小)

2 0 0 3(数组元素)



输出:

2 3 0 0(预期输出)



我的输出:

0 0 0 0



编辑:请给我更正的代码。



我尝试过:



So I have to get the size of the array and the array elements from the user and print the output such that the array elements' zeros are moved to the end.

But all I'm getting are only zeros.

Example:
4 (size of array)
2 0 0 3 (array elements)

output:
2 3 0 0 (expected output)

My output:
0 0 0 0

Please give me the corrected code.

What I have tried:

import java.io.*;
import java.util.*;
public class PartitionZeroElement {  
     
    static void moveZeroElementToEnd(int[] array) {  
        int size = array.length;  
        int count = 0;  
  
        for (int i = 0; i < size; i++) {  
            if (array[i] != 0) {  
                array[count++] = array[i];  
            }  
        }  
  
        while (count < size)  
            array[count++] = 0;  
    }  
  
    public static void main(String[] args) {  
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        int[] array = new int[t] ; 
        moveZeroElementToEnd(array);  
  
        System.out.println("Array After Zero Elements moved to end :");  
  
        for (int i = 0, size = array.length; i < size; i++)  
            System.out.print(array[i] + " ");  
    }  
}  

推荐答案

您忘记从用户输入中读取数组元素:

You forgot to read the array elements from the user input:
// This is missing in your code:
for (int i = 0; i < t; i++) {  
    array[i] = in.nextInt();
}
//
moveZeroElementToEnd(array);


使用从升序到降序的插入排序
Use a insertion sort from ascending to descending order


这篇关于如何将数组中的所有零移动到最后? (JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆