排序的零,负和正号的数组 [英] Sorting an array of zeros, negative and positive numbers

查看:68
本文介绍了排序的零,负和正号的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中的数组

int num[] = {5, -3, 0, -18, 1, 2, 0};

我想使它看起来像这些

I want to make it look like these

{-3, -18, 0, 0, 5, 1, 2}

什么我现在是这样的。

What I have right now is this

for (int i=0; i<num.length;i++)
    {
        for (int j=1; j<num.length-1;j++)
        {
            if (num[j]<0)
            {
                temp=num[j];
                c=num[j-1];
                num[j-1]=temp;
                num[j]=c;
            } 
        }  
    }

但是,这种只负数,而且我找不到解决如何排序零。
你能帮我吗?

But this sort just negative numbers, and I can't find solution how to sort zeros. Can you help me, please?

推荐答案

您可以使用 Arrays.sort()使用自定义的比较,这将preserve的用等号号码的顺序:

You can use Arrays.sort() with a custom comparator, which will preserve the order of the numbers with equal sign:

Integer[] num = {5, -3, 0, -18, 1, 2, 0};
Arrays.sort(num, (a, b) -> Integer.signum(a) - Integer.signum(b));
System.out.println(Arrays.toString(num)); // [-3, -18, 0, 0, 5, 1, 2]

编辑:既然事实证明,OP只是想一个普通的那种,这将是

Since it turns out that OP just wanted an ordinary sort, that would be

Arrays.sort(num);

这篇关于排序的零,负和正号的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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