VOOZH about

URL: https://www.geeksforgeeks.org/java/sort-an-array-according-to-other-in-java/

⇱ Sort an Array According to Another Array in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort an Array According to Another Array in Java

Last Updated : 29 Jan, 2026

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.

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.

Comment
Article Tags:
Article Tags: