对混合整数和字符串的ArrayList进行排序,同时保留字符串和整数的相对排序

Kal*_*ope 9 java sorting algorithm arraylist

考虑下面给出的一个arraylist

unsortedList = {6,"ball",3,1,"apple","cat",4} 
Run Code Online (Sandbox Code Playgroud)

这需要排序

sortedList = {1,"apple",3,4,"ball","cat",6}
Run Code Online (Sandbox Code Playgroud)

按字母顺序排序字符串.按升序对数字排序.但请注意以下条件:

  • 如果未排序列表中存在整数,则它必须是排序列表中的整数.
  • 如果未排序列表中存在字符串,则它必须是排序列表中的字符串.

请注意,在上面的示例中,所有整数都按升序排序,所有字符串都按升序排序,但整数和字符串的相对位置与之前相同.

tem*_*def 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++));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!