Java tutorial
//package com.java2s; //License from project: Apache License import java.util.Arrays; import java.util.Collections; import java.util.List; public class Main { /** * Shift objects in the list, objects will try to move to the furthest distance. * <pre> * e.g. ABCED -> Shift AC with offset=5 -> BEDAC * </pre> * * @param list list * @param indexArray object index array * @param offset offset value can be positive or negative */ public static void shiftItemsAsMuchAsPossible(List<?> list, int[] indexArray, int offset) { Arrays.sort(indexArray); if (offset > 0) { int last = list.size(); for (int i = indexArray.length - 1; i >= 0; i--) { last = shiftItem(list.subList(0, last), indexArray[i], offset); } } else { int last = -1; for (int i = 0; i < indexArray.length; i++) { int index = indexArray[i] - (last + 1); last = shiftItem(list.subList(last + 1, list.size()), index, offset); } } } /** * Shift object in the list * * @param list list * @param index object index * @param offset offset value can be positive or negative. * @return new index of the object */ public static int shiftItem(List<?> list, int index, int offset) { if (offset == 0 || index < 0) { return 0; } if (offset > 0) { int end = index + offset + 1; if (end > list.size()) { end = list.size(); } Collections.rotate(list.subList(index, end), -1); return end - 1; } else { int start = index + offset; if (start < 0) { start = 0; } Collections.rotate(list.subList(start, index + 1), 1); return start; } } }