In Java, how can I sort an array based on the index order of another sorted array? For instance, if I have:
arr1 = {26, 8, 3}
arr2 = {3, 1, 2}
arr3 = {57, 23, 11}
arr4 = {78, 2, 61}
and I sort arr2 in ascending order to be
arr2 = {1, 2, 3}
and I want the other to then be:
arr1 = {8, 3, 26}
arr3 = {23, 11, 57}
arr4 = {2, 61, 78}
How can I accomplish this is Java? I know I would save the new sorted arrays into new instances. Anything helps, thanks!
Here is one way to do it.
Integer[] indices = IntStream.range(0, arr2.length)
.boxed()
.sorted(Comparator.comparing(i -> arr2[i]))
.toArray(Integer[]::new);
List<int[]> list = Stream
.of(arr1, arr2, arr3, arr4).map(arr -> Stream
.of(indices)
.mapToInt(i -> arr[i])
.toArray())
.collect(Collectors.toList());
list.forEach(arr -> System.out.println(Arrays.toString(arr)));
Prints
[8, 3, 26]
[1, 2, 3]
[23, 11, 57]
[2, 61, 78]
You could also place the arrays in another "2D"
array and do as follow with the same result.
int[][] arrays = { arr1, arr2, arr3, arr4 };
List<int[]> list = Arrays
.stream(arrays)
.map(arr -> Stream
.of(indices)
.mapToInt(i -> arr[i])
.toArray())
.collect(Collectors.toList());
Found answer elsewhere
public class SortTogether{
// sort the array a, and also update the elements in array b, c, and d
// based on the index of a
public static void bubbleSort(int[] a, int[] b, int[] c, int[] d) {
for(int i=0; i<a.length; i++){
for(int j=0; j<a.length-i-1;j++){
if(a[j]>a[j+1]){
// when you are swapping the elements
int t = a[j]; a[j]=a[j+1];a[j+1]=t;
// swap the elements in the other arrays as well
// so the elements in other array will also stay together
t = b[j]; b[j]=b[j+1];b[j+1]=t;
t = c[j]; c[j]=c[j+1];c[j+1]=t;
t = d[j]; d[j]=d[j+1];d[j+1]=t;
}
}
}
}
public static void main(String a[]) {
int[] arr1 = {26, 8, 3};
int[] arr2 = {3, 1, 2};
int[] arr3 = {57, 23, 11};
int[] arr4 = {78, 2, 61};
System.out.println("Before sort");
display(arr1);
display(arr2);
display(arr3);
display(arr4);
bubbleSort(arr2,arr1,arr3,arr4);
System.out.println("\nAfter sort");
display(arr1);
display(arr2);
display(arr3);
display(arr4);
}
public static void display(int[] arr) {
for (int num : arr) System.out.printf("%4d", num);
System.out.println();
}
}
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.