# Processing Java mode return Index of sorted array

**URL:** <https://discourse.processing.org/t/processing-java-mode-return-index-of-sorted-array/43063>\
**Category:** Coding Questions\
**Created:** [October 26, 2023, 2:44am UTC](https://discourse.processing.org/t/processing-java-mode-return-index-of-sorted-array/43063 "2023-10-26T02:44:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![seany](https://avatars.discourse-cdn.com/v4/letter/s/ba8739/32.png) [@seany](https://discourse.processing.org/u/seany)\
**Post date:** [October 26, 2023, 2:44am UTC](https://discourse.processing.org/t/processing-java-mode-return-index-of-sorted-array/43063/1 "2023-10-26T02:44:55Z")

</div>

Hello

This is my first post. I am using: `Processing 4 1293` for Linux

In Java mode, I want to sort an array, but want to get the index of the sorted array. Example:

```auto
array = {1,4,2,4,1,4,3,4,5}; // this is my input}
sortedArrayIndex = {0,4,2,6,1,3,5,7,8} ; // this is what i want

```

If I use the built in `sort` function, it will return me the array `{1,1,2,3,4,4,4,4,5}` - but what I want is an array of indices of elements in the original array, as they’d appear if they were sorted.

In the input array, same elements cna appear multiple times. In our example - 1 is smallest but appears in indices 0 and 4 - hence the first two items in output array is 0 and 4.

I would like these indices of similar elements to be sorted as well - that is, 0 comes before 4, even tho elements 4 and 0 are the same, and 4 coming before 0 would also have represented a sorted array.

I would like some help on this. Thank you.

---

<div class="post-metadata">

**Author:** ![micuat](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micuat/32/19407_2.png) [@micuat](https://discourse.processing.org/u/micuat)\
**Post date:** [October 31, 2023, 9:13am UTC](https://discourse.processing.org/t/processing-java-mode-return-index-of-sorted-array/43063/2 "2023-10-31T09:13:39Z")

</div>

I found a solution here

> <https://stackoverflow.com/questions/951848/java-array-sort-quick-way-to-get-a-sorted-list-of-indices-of-an-array>

in processing it would be

```java
import java.util.Arrays;
import java.util.Comparator;
void setup() {
  final Integer[] idx = {0,1,2,3,4,5,6,7,8};
  Integer[] array = {1,4,2,4,1,4,3,4,5}; // this is my input
  // sortedArrayIndex = {0,4,2,6,1,3,5,7,8} ; // this is what i want

  Arrays.sort(idx, new Comparator<Integer>() {
      @Override public int compare(final Integer o1, final Integer o2) {
          return Integer.compare(array[o1], array[o2]);
      }
  });
  
  println(idx);
}

```
