I have an array of Strings that are instances of a class from external code that I would rather not change.
I also have an array of ints that was generated by calling a function on each object. So I have
A: [string1, string2, string3]
And
B: [40, 32, 34]
How do I easily sort A such that it is sorted in by the values of B. I have boost available. I want to sort A such that it is in the order:
[string2, string3, string1]
In javascript you could do this like:
B.sort(function(a,b){return A[B.indexOf(a)] < A[B.indexOf(b)];});
Method 1 (Using Sorting and Binary Search)Create a temporary array temp of size m and copy the contents of A1[] to it. Create another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to A1[]. Initialize the output index ind as 0.
You can sort within the array using Arrays. sort() method, or if you want to sort in a different array, you can take following steps: Copy the array to new array. Sort the new array and then sort.
The relative order means that in respect to the original order, the new partitioned set will maintain that ordering. In your example that means {1,7,3,10,9,6} become {10,6,1,7,3,9}
In java 8, you can do this
with a lambda:
String[] strings = new String[]{"string1", "string2", "string3"};
final int[] ints = new int[]{40, 32, 34};
final List<String> stringListCopy = Arrays.asList(strings);
ArrayList<String> sortedList = new ArrayList(stringListCopy);
Collections.sort(sortedList, (left, right) -> ints[stringListCopy.indexOf(left)] - ints[stringListCopy.indexOf(right)]);
Or better, with Comparator:
String[] strings = new String[]{"string1", "string2", "string3"};
final int[] ints = new int[]{40, 32, 34};
final List<String> stringListCopy = Arrays.asList(strings);
ArrayList<String> sortedList = new ArrayList(stringListCopy);
Collections.sort(sortedList, Comparator.comparing(s -> ints[stringListCopy.indexOf(s)]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With