简体   繁体   English

以升序对数组进行排序[Java]

[英]Sort array in ascending order [Java]

So recently I came across a problem when trying to sort in ascending order of an array: 所以最近我在尝试按数组的升序排序时遇到一个问题:

private PlaneSeat[] sortSeats() {
    PlaneSeat[] tempAr = seat;
    int temp, tempI, tempJ;

    for (int i = 0; i < tempAr.length; i++) {
        for (int j = 0; j < tempAr.length; j++) {
            if (tempAr[i].isOccupied()) {
                tempI = tempAr[i].getCustomerID();
                tempJ = tempAr[j].getCustomerID();
                if (tempI < tempJ) {
                    temp = tempI;
                    tempI = tempJ;
                    tempJ = temp;
                }
            }
        }
    }
    return tempAr;
}

What I am trying to do is I am assigning seat array to a temporary array because I do not want to override the value in original array. 我想做的是将席位数组分配给一个临时数组,因为我不想覆盖原始数组中的值。 Then, I am trying to compare the customerID in temporary array and sort according to the ascending order of customerID. 然后,我尝试比较临时数组中的customerID,并根据customerID的升序进行排序。 Then, from my main method, I am calling it: 然后,从我的主要方法中调用它:

tempAr = sortSeats();
        for (int i = 0; i < tempAr.length; i++) {
            if (tempAr[i].isOccupied()) {
                System.out.println("SeatID " + tempAr[i].getSeatID()
                        + " assigned to CustomerID "
                        + tempAr[i].getCustomerID());
            }
        }

However, with these, it does not sort according to the customerID, it still returning me the original array. 但是,有了这些,它不会根据customerID进行排序,它仍然返回原始数组。 Any ideas? 有任何想法吗?

Thanks in advance. 提前致谢。

here you just swap the temp variable but didn't set it to original array: 在这里,您只是交换了temp变量,但没有将其设置为原始数组:

if (tempI < tempJ) {
                temp = tempI;
                tempI = tempJ;
                tempJ = temp;
 }

so I think you should swap the PlaneSeat in your array: 所以我认为您应该在数组中交换PlaneSeat:

if (tempI < tempJ) {
               PlaneSeat tempSeat = tempAr[i];
               tempAr[i] = tempAr[j];
               tempAr[j] = tempSeat;
 }

temp, tempI etc. are primitive variables so they get reassigned but the original array doesn't change. temp,tempI等是原始变量,因此可以重新分配它们,但原始数组不会更改。 What you need is to switch array data: 您需要切换阵列数据:

if (tempI < tempJ) {
   tempAr[i] = tempj;
   tempAr[j] = tempI;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM