Custom Priority Sort

Sorting Algorithms Custom Sort

Problem: Custom Priority Sort

On January 12, 2025, as we continue to refine our algorithms post-New Year, you are tasked with implementing a custom sorting algorithm with a twist. Given an array of integers and a separate array representing priority values, sort the input array such that:

  1. All numbers that appear in the priority list come first, maintaining the order in which they appear in the priority list. If a number from the priority list occurs multiple times in the input, all occurrences should appear in this section, preserving their relative order from the original array.
  2. Numbers not included in the priority list should be placed after, sorted in ascending order.

Example:

  • Input: arr = [5, 3, 9, 1, 3, 7, 1], priority = [3, 1]
  • Output: [3, 3, 1, 1, 5, 7, 9]

Explanation:

  • All instances of 3 and 1 are moved to the front in the order specified by the priority list.
  • Remaining numbers [5, 7, 9] are sorted in ascending order and appended.

Function Signature:

Implement a function that takes in two arrays and returns the sorted array based on the above rules.


Input:

  • arr: An array of integers.
  • priority: An array of unique integers dictating the order of prioritized elements.

Output:

  • A sorted array of integers as per the specifications.

Happy coding and enjoy the challenge!