Java: sort List from index to index

Just use .subList() to get a "backed" view onto the main list, then call sort. The sublist is "write-through" so changes are reflected in the original.

List<Integer> foo = Arrays.asList(5,3,1,6,2,1);
Collections.sort(foo.subList(0, 3)); // sort first 3 elements 
System.out.println(foo);
Collections.sort(foo.subList(3, 6)); // sort last 3 elements
System.out.println(foo);

Output

[1, 3, 5, 6, 2, 1]
[1, 3, 5, 1, 2, 6]

You can use subList() on your original list, then sort the sublist and it will reflect on your original list without having to write back.


Copying the list entries indexed by fromIndex to toIndex to a new List (by using list.subList(fromIndex, toIndex)), sort it and overwrite the old list entries

No, there is no object copy when you call list.subList. The function subList creates a view backed by the original list. Only reference copies; no actual object copies.

Any operations (sorting) on the view will be reflected on the original list.

 public static void main(String[] args) throws Exception {
    List<Integer> list = Arrays.asList(1, 9, 8 ,7, 2, 3, 4);

    // [9, 8 ,7] => [7, 8, 9]
    sortList(list, 1, 4);

    System.out.println(list);       // [1, 7, 8, 9, 2, 3, 4]
  }

  public static <T extends Comparable<T>> void sortList(
      List<T> list, int fromIndex, int toIndex) {
    Collections.sort(list.subList(fromIndex, toIndex));
  }