Given two arrays of equal size, an integer array a[] and a character array b[], each character is associated with an integer at the same index.
- Sort the character array b[] according to the ascending order of the integer array a[].
- The one-to-one correspondence between integers and characters must be preserved after sorting.
Example:
Input: a[] = {3, 1, 2}, b[] = {'G', 'E', 'K'}
Output: {'E', 'K', 'G'}
Explanation: After sorting the integer array a[] in ascending order as {1, 2, 3}, the characters in b[] are rearranged to match this order, resulting in {'E', 'K', 'G'}.
Approach
Follow these steps to sort the character array according to the integer array:
- Define a Pair class containing an integer and its corresponding character.
- Create an array of Pair objects for all elements in the arrays.
- Sort the Pair array using the integer value as the key.
- Extract the characters from the sorted Pair array and update the character array.
import java.util.*;
// Class to store integer and corresponding character
class Pair {
int num;
char ch;
Pair(int num, char ch)
{
this.num = num;
this.ch = ch;
}
}
public class SortCharByInt {
// Function to sort character array according to integer
// array
static void sortCharByInt(int[] a, char[] b)
{
int n = a.length;
Pair[] pairs = new Pair[n];
// Store integer and character as pairs
for (int i = 0; i < n; i++) {
pairs[i] = new Pair(a[i], b[i]);
}
// Sort pairs based on integer values
Arrays.sort(pairs,
Comparator.comparingInt(p -> p.num));
// Update character array according to sorted pairs
for (int i = 0; i < n; i++) {
b[i] = pairs[i].ch;
}
}
public static void main(String[] args)
{
int[] a = { 3, 1, 2 };
char[] b = { 'G', 'E', 'K' };
sortCharByInt(a, b);
System.out.println("Sorted character array: "
+ Arrays.toString(b));
}
}
Output
Sorted character array: [E, K, G]
- Time Complexity: O(n log n)
- Space Complexity: O(n)
Note: The sorting order can be either ascending or descending based on the problem requirement or user’s choice.