首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >集合排序-正、0、负序

问集合排序-正、0、负序
EN

Stack Overflow用户
提问于 2013-01-16 01:38:20
回答 4查看 1.3K关注 0票数 0

我有一批员工。每个员工都有一个ID。此ID号的格式为-x >= 0 >= x。我必须将雇员排序为0...x -1...x。我该怎么做呢??

代码语言:javascript
复制
List<Employee> empSort = new ArrayList(em.getEmployees());
Collections.sort(empSort, new Comparator<Employee>() {
                @Override
                public int compare(Employee p1, Employee p2) {
                   // WHAT LOGIC SHOULD I DO THERE TO HAVE THEM
                                      SORTED AS 0...x -1....-x
                }
            });
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-01-16 02:41:56

在晚餐的时候考虑了一下,我更喜欢这样。

代码语言:javascript
复制
int sign1 = (p1 >= 0) ? 1 : -1;
int sign2 = (p2 >= 0) ? 1 : -1;

int result = Integer.compare(sign2, sign1);

if( result == 0){
    // same sign
    result = sign1 * Integer.compare(p1, p2);
}
return result;

输出仍然是:

代码语言:javascript
复制
[0, 0, 0, 1, 3, 5, -1, -2]
票数 2
EN

Stack Overflow用户

发布于 2013-01-16 01:44:54

你能不能不做三个测试?

Non-negative先于negative。如果恰好有一个为负,则返回return。

如果两者都为负值,则较大的值出现在较小的值之前。

如果两者都为非负值,则较小的值位于较大的值之前。

票数 1
EN

Stack Overflow用户

发布于 2013-01-16 01:57:30

当第一个参数小于、等于或大于第二个参数时,Compare返回负整数、零或正整数。

代码语言:javascript
复制
if( p1.id * p2.id < 0 ) {
    // opposite sign
    // if p1 is negative, p2 is positive, p1 is greater than p2
    // otherwise p1 is positive, p2 is negative, p1 is less than p2
    return -p1.id;
}
if( p1.id > 0 && p2.id > 0 || p1.id + p2.id >= 0) {
    // both positive, normal ordering or a zero and a positive number, also normal ordering
    return p1.id - p2.id;
}
if( p1.id <0 && p2.id < 0 ){
    // both negative, inverse ordering
    return p2.id - p1.id;
}
// zero and a negative number, zero comes first
if( p1.id == 0 ) {
    return -1;
}
return 1;

0,0,0,1,3,5,-1,-2

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14343513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档