考虑下面给出的一个arraylist
unsortedList = {6,"ball",3,1,"apple","cat",4}
这需要排序到
sortedList = {1,"apple",3,4,"ball","cat",6}
按字母顺序对字符串进行排序。按升序对数字排序。但请注意以下条件:
请注意,在上面的示例中,所有整数都按升序排序,所有字符串都按升序排序,但整数和字符串的相对位置与之前相同。
答案 0 :(得分:8)
此处的一个选项是执行以下操作:
这非常有效 - 你只需要做两种。这是一些代码:
public void relativeOrderSort(List<Object> list) {
/* Create a list of just the integers and just the strings
* from the original list.
*/
List<Integer> intList = new ArrayList<Integer>();
List<String> strList = new ArrayList<String>();
for (Object obj: list) {
if (obj instanceof Integer) {
intList.add((Integer) obj);
} else if (obj instanceof String) {
strList.add((String) obj);
} else {
throw new IllegalArgumentException("List has a non-int, non-string member.");
}
}
/* Sort the lists. */
Collections.sort(intList);
Collections.sort(strList);
/* Merge the lists back together. */
int intIndex = 0, strIndex = 0;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) instanceof Integer) {
list.set(i, intList.get(intIndex++));
} else {
list.set(i, strList.get(strIndex++));
}
}
}
希望这有帮助!
答案 1 :(得分:3)
伪代码:
Create a list of the indices pointing to integers ({0,2,3,6} in your case - indxInt )
Sort the integers ({6,3,1,4} turns into {1,3,4,6})
Put them back at the locations given by the pointers:
sorted(indxInt(0)) = 1;
sorted(indxInt(1)) = 3;
sorted(3) = 4; // indxInt(2) == 3
sorted(6) = 6; // indxInt(3) == 6
Repeat for the strings