Sort an array according to the order defined by another array in C++


In this section we will see another sorting problem. Suppose we have two arrays A1 and A2. We have to sort A1 in such a way that the relative order among the elements will be same as those are in A2. If some elements are not present in A2, then they will be appended after the sorted elements. Suppose A1 and A2 are the following −

A1 = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8}
A2 = {2, 1, 8, 3}

After the sorting A1 will be like below −

A1 = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}

To solve this problem, we will create our custom compare method. That method will compare and place the elements in the array. The comparison logic will be like below −

  • if num1 and num2 both are in A2, then number with the lower index in A2 will be treated as smaller than the other number
  • If either num1 or num2 is present in A2, then that number will be treated as smaller, than the other, which is does not present in A2.
  • If both are not present in A2, then natural ordering will be used.

Algorithm

compare(num1, num2):
Begin
   if both num1 and num2 are present in A2, then
      return index of num1 – index of num2
   else if num1 is not in A2, then
      return -1
   else if num2 is not in A1, then
      return 1
   else
      num1 – num2
End

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
int size = 5;
int A2[5]; //global A2 will be used in compare function
int search_index(int key){
   int index = 0;
   for(int i = 0; i < size; i++){
      if(A2[i] == key)
      return i;
   }
   return -1;
}
int compare(const void *num1, const void *num2){
   int index1 = search_index(*(int*)num1);
   int index2 = search_index(*(int*)num2);
   if (index1 != -1 && index2 != -1)
   return index1 - index2;
   else if (index1 != -1)
      return -1;
   else if (index2 != -1)
      return 1;
   else
      return (*(int*)num1 - *(int*)num2);
}
main(){
   int data[] = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8};
   int n = sizeof(data)/sizeof(data[0]);
   int a2[] = {2, 1, 8, 3};
   int n2 = sizeof(a2)/sizeof(a2[0]);
   for(int i = 0; i<n2; i++){
      A2[i] = a2[i];
   }
   qsort(data, n, sizeof(int), compare);
   for(int i = 0; i<n; i++){
      cout << data[i] << " ";
   }
}

Output

2 2 1 1 8 8 3 5 6 7 9

Updated on: 25-Sep-2019

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements