I have a 2D array called distance[][]
It holds my values in column 0:
Example:
{ 5
7
3
9 }
It seems like a 1D array, however I've converted it into a 2D array in order to be able to keep track of my indexes.
The way I access my first value is distance[0][0].
My question is: how can I keep track of the original index positions if I were to sort my array. I was under the impression that I may need to create a corresponding list of numbers in ascending order which correspond with the position my of distance values.
What would I do after that?
最简单的解决方案是创建一个包含该项目及其对应索引的Pair
类,然后将这个Pair
类的列表保留在两个不同的list
而不是对其中的一个进行排序。因为在Java中,您可以使用引用而不创建复制对象,这应该很容易。现在排序列表将包含值和根据值排序的相应索引,而未排序列表将按照您输入的顺序Pair
,即根据索引排序。
All you need is to use comparator. Consider below code -
Arrays.sort(arr, new java.util.Comparator<int[]>(){
public int compare(int[] a,int[] b){
return a[0]-b[0];
}
});
arr
is your orginial 2d array, where first column contains the number to sorted and second column contains index
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.