简体   繁体   中英

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. 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. Any ideas?

Thanks in advance.

here you just swap the temp variable but didn't set it to original array:

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

so I think you should swap the PlaneSeat in your array:

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. What you need is to switch array data:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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