简体   繁体   中英

What is the best way to sort an ArrayList based on a already sorted ArrayList?

For example, I have two arrays:

arrayA[{name: "apple", value: 1}, {name: "banana", value: 2} , {name: "pear", value: 3}] arrayB[{name: "banana", value: 4}, {name: "apple", value: 5} , {name: "pear", value: 3}]

The end result should have arrayB look like this:

arrayB[{name: "apple", value: 5}, {name: "banana", value: 4} , {name: "pear", value: 3}]

The best solution I can think of is a double for loop, one to track my location in arrayA , another to track my location in arrayB :

for (int i = 0; i < arrayB.size(); i++) {
    if (!arrayB.get(i).getName().equals(arrayA.get(i).getName()) {
        Object temp = arrayB.get(i);

        for (int j = i + 1; j < arrayB.size(); j++) {
            if (arrayB.get(j).getName().equals(arrayA.get(i).getName())) {
                arrayB.set(i, arrayB.get(j));
                arrayB.set(j, temp);
            }
        }
    }
}

Is there a more efficient way of doing this?

Another example would be if I had these two arrays:

arrayA[{name: "pear", value: 1}, {name: "apple", value: 2} , {name: "banana", value: 3}] arrayB[{name: "banana", value: 4}, {name: "apple", value: 5} , {name: "pear", value: 3}]

Then arrayB should look like this: (ie. It's save to assume arrayA is already sorted.) arrayB[{name: "pear", value: 3}, {name: "apple", value: 5} , {name: "banana", value: 4}]

Your solution is has O(n^2) time complexity - those nested loops will be very slow for large lists.

However, with the aid of a HashMap , an O(n) solution is possible.

Map<String, NameAndValue> map = new HashMap<>();
for (NameAndValue x : arrayB)
    map.put(x.getName(), x);

for (int i = 0; i < arrayA.size(); i++) 
    arrayB.set(i, map.get(arrayA.get(i).getName()));

This only works if the lists have the same fruit in different orders and no fruit appears twice.

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