繁体   English   中英

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

[英]Sort array in ascending order [Java]

所以最近我在尝试按数组的升序排序时遇到一个问题:

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;
}

我想做的是将席位数组分配给一个临时数组,因为我不想覆盖原始数组中的值。 然后,我尝试比较临时数组中的customerID,并根据customerID的升序进行排序。 然后,从我的主要方法中调用它:

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());
            }
        }

但是,有了这些,它不会根据customerID进行排序,它仍然返回原始数组。 有任何想法吗?

提前致谢。

在这里,您只是交换了temp变量,但没有将其设置为原始数组:

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

所以我认为您应该在数组中交换PlaneSeat:

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

temp,tempI等是原始变量,因此可以重新分配它们,但原始数组不会更改。 您需要切换阵列数据:

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

暂无
暂无

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

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