How to sort an array and keep track of the index in java

后端 未结 3 957
一整个雨季
一整个雨季 2021-01-01 23:29

I am trying to sort (decreasing) an array of integers but keeping track of the original index.

I mean, for example if I have this array:

b[         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 23:58

    The following answer provides the main steps to overcome the issue explained in the question without details code provided.

    • you can create custom Class that has two attributes value and index. where value is the original attribute value and index is the position before sorting.
    • create an ArrayList of this Class.
    • add the new objects of the created Class with the wanted value and index.

    Note: one possible way to set the index value is to iterate through the Arraylist and set the value of index using loop index.

    • sort the Arraylist using specialComparable based on value attribute.

    now after sorting you can know the previousindex of any entry by invoking its index attribute.

提交回复
热议问题