signed

QiShunwang

“诚信为本、客户至上”

java按照给定数组顺序给另外一个数组排序

2021/3/21 8:54:10   来源:

1、今天遇到一道笔试题,按照一个给定数组里的顺序给另外一个数组排序,要求:为了节省空间,不能额外新建数组

//数组中实体对象
public class Test {
    private Integer id;
    private String name;

    public Test(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Test{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

//排序算法
public class TestDemo {
    public static void main(String[] args) {
        Test[] arr1 = {
                new Test(1,"david"), new Test(2,"alin"), new Test(3,"ming"),
                new Test(4,"lili"), new Test(5,"amy")
        };
        System.out.println(Arrays.asList(arr1).toString());
        Integer[] arr2 = {5, 1, 4, 3, 2};
        for(int i=0;i<arr2.length;i++){
            int a = arr2[i];
            for (int j =0;j<arr1.length;j++){
                if(arr1[j].getId()==a){
                    Test t = arr1[j];
                    Test t1 = arr1[i];
                    arr1[i] =t;
                    arr1[j] = t1;
                }
            }
        }
        System.out.println("=============");
        System.out.println(Arrays.asList(arr1).toString());
    }
}