-2

So supposing I have an arraylist named arr and it contains integers

arr[0] = 7  
arr[1] = 4  
arr[2] = 1  
arr[3] = 3

I want to sort them but excluding the first array which is arr[0] so I want the array to be like this

arr[0] = 7  
arr[1] = 1  
arr[2] = 3  
arr[3] = 4

Any ideas how to do it? Could this be done by using a comparator?

Steven
  • 518
  • 2
  • 4
  • 12
  • 1
    pass the array element with second element – shiv Sep 14 '17 at 13:42
  • you may have a look here: [Sort an integer array, keeping first in place](https://stackoverflow.com/questions/44440357/sort-an-integer-array-keeping-first-in-place) – Nina Scholz Sep 14 '17 at 13:50

1 Answers1

1

If you are starting with an array, you can use Arrays.asList(T...) to construct a List view of your array, backed by the real array.

You can use List#subList(fromIndex, toIndex) to create a view of the list starting from the second item.

If you sort this sublist, your original list (as well as your original array, if you used asList, above) will be sorted starting at the second item.

So assuming arr is an ArrayList<Integer>, all you need is:

arr.subList(1, arr.size()).sort(your_comparator);
AJNeufeld
  • 8,526
  • 1
  • 25
  • 44