-4

i would like to know how this task can be done as easy as possible with Java:

  1. Splice out a part of an ArrayList (by index)
  2. Reverse this splice
  3. Overwrite index range from the original list with the spliced/reversed one.

For example, i have a list with these numbers:

[3,2,8,9]

Splice out:

[2,8,9]

reverse it:

[9,8,2]

put it back together:

[3,9,8,2]

Best regards

binaryBigInt
  • 1,526
  • 2
  • 18
  • 44
  • 1
    Possible duplicate of [Breaking out of nested loops in Java](http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java) – Luis Sieira Apr 13 '17 at 15:36

1 Answers1

1

Here is generic code for your requirement with complexity of O(n) -

<E> List<E> spliceAndReverse(List<E> list, int startIndex, int endIndex){
        while(startIndex < endIndex){
            E e = list.get(startIndex);
            list.set(startIndex, list.get(endIndex));
            list.set(endIndex, e);
            startIndex++;
            endIndex--;
        }   
        return list;
    }

We can also use sublist, here is code for that -

static <E> List<E> spliceAndReverseUsingSubList(List<E> list, int startIndex, int endIndex){
        List<E> subList =  list.subList(startIndex, endIndex+1);
        Collections.reverse(subList);
        List<E> resultList = new ArrayList<>(list.subList(0, startIndex));
        resultList.addAll(subList);
        if(list.size() != endIndex+1){
        resultList.addAll(list.subList(endIndex+1, list.size()));
        }
        return resultList;
    }


See Example here - http://blog.deepaktripathi.in/uncategorized/reverse-arraylist-between-2-given-indexes/

Note - Before asking question on platform please make sure you have tried enough.

Deepak Tripathi
  • 600
  • 2
  • 4
  • 22
  • How can i fix the problem that the inner numbers are reversed twice? For example this array: `[2,5,4,3,1]` is reversed to `[2,1,4,3,5]` even though it should be `[2,1,3,4,5]` (`startIndex`=1, `endIndex` = 4). – binaryBigInt Apr 13 '17 at 15:37