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

Get Prepinsta Prime

Get all 200+ courses offered by Prepinsta

Never Miss an OffCampus Update

Get OffCampus Updates on Social Media from PrepInsta

Follow us on our Media Handles, we post out OffCampus drives on our Instagram, Telegram, Discord, Whatsdapp etc.

Get Hiring Updates
Amazon,Google,Delottie & 30+companies are hiring ! Get hiring Updates right in your inbox from PrepInsta

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others.

Get PrepInsta Prime Subscription

Get access to all the courses that PrepInsta offers, check the out below -

Companies

TCS, Cognizant, Delloite, Infosys, Wipro, CoCubes, KPMG, Amazone, ZS Associates, Accenture, Congnizant & other 50+ companies

Programming

Data Structures, Top 500 Codes, C, C++, Java Python & other 10+ subjects

Skills

Full Stack Web Development, Data Science, Machine Learning, AWS Cloud, & other 10+ skills and 20+ projects

OffCampus Updates

Never Miss OffCampus Updates

Get OffCampus Update from PrepInsta

Follow us on our Social Media Handles

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

Here we will learn about how to Sort an array according to the order defined by another array in C. The elements in array X has to be printed according to the sequence of order of elements specified in array Y, the rest of the elements, remaining in array X are printed at the end. We are given an array and we have to sort the array according to the order defined by another array.

Sort an array according to the order defined by another array

Method Discussed :

  • Method 1 : Using Sorting and Binary searching.
  • Method 2 : By making customized comparator.

Method 1 :

  • Declare a temporary array temp of size m and copy the contents of arr1[] to it.
  • Declare another array visited[] and initialize all entries in it as false. visited[] is used to mark those elements in temp[] which are copied to arr1[].
  • Sort temp[] using any sorting technique
  • Declare the output index ind as 0.
  • Do following for every element of arr2[i] in arr2[] 
    • Binary search for all occurrences of arr2[i] in temp[], if present then copy all occurrences to arr1[ind] and increment ind. Also mark the copied elements visited[]
  • Copy all unvisited elements from temp[] to arr1[]

Method 1 : Code in C

#include<stdio.h>
 
int first(int arr[], int low, int high, int x, int n)
{
 
    if (high >= low) {
 
        int mid = low + (high - low) / 2;
 
        if ((mid == 0 || x > arr[mid - 1]) && arr[mid] == x)
            return mid;
 
        if (x > arr[mid])
            return first(arr, (mid + 1), high, x, n);
 
        return first(arr, low, (mid - 1), x, n);
    }
 
    return -1;
}
 
void sortAccording(int A1[], int A2[], int m, int n)
{
    int temp[m], visited[m];
    for (int i = 0; i < m; i++) {
        temp[i] = A1[i];
        visited[i] = 0;
    }
    
    for(int i=0; i<m; i++){
        for(int j=i+1; j<m; j++){ if(temp[i]>temp[j]){
                int x= temp[i];
                temp[i]= temp[j];
                temp[j]=x;
            }
        }
    } 
    
    int ind = 0;
 
    for (int i = 0; i < n; i++) {
        int f = first(temp, 0, m - 1, A2[i], m);
 
        if (f == -1)
            continue;
 
        for (int j = f; (j < m && temp[j] == A2[i]); j++) {
            A1[ind++] = temp[j];
            visited[j] = 1;
        }
    }
 
    for (int i = 0; i < m; i++)
        if (visited[i] == 0)
            A1[ind++] = temp[i];
}
 
void printArray(int arr[], int n)
{
 
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
        
    printf("\n");
}
 
// Driver Code
int main()
{
    int arr1[] = { 20, 1, 20, 5, 7, 1, 9, 39, 6, 18, 18 };
    int arr2[] = { 20, 1, 18, 39 };
    int m = sizeof(arr1) / sizeof(arr1[0]);
    int n = sizeof(arr2) / sizeof(arr2[0]);
 
    sortAccording(arr1, arr2, m, n);
    printArray(arr1, m);
    return 0;
}

Output

20 20 1 1 18 18 39 5 6 7 9

Method 2 :

In this method we will create our own customized compare method.

Method 2 : Code in C

#include <stdio.h>
#include <stdlib.h>
 
int arr2[4];
 
// size of arr2[]
int size = 5;
 
int search(int key)
{
    int i = 0, idx = 0;
    for (i = 0; i < size; i++)
        if (arr2[i] == key)
            return i;
    return -1;
}
 
int compareByA2(const void* a, const void* b)
{
    int idx1 = search(*(int*)a);
    int idx2 = search(*(int*)b);
    if (idx1 != -1 && idx2 != -1)
        return idx1 - idx2;
    else if (idx1 != -1)
        return -1;
    else if (idx2 != -1)
        return 1;
    else
        return (*(int*)a - *(int*)b);
}
 
void sortA1ByA2(int arr1[], int size1)
{
    qsort(arr1, size1, sizeof(int), compareByA2);
}
 
// Driver program to test above function
int main()
{
    int arr1[] = { 20, 1, 20, 5, 7, 1, 9, 39, 6, 18, 18 };
    arr2[0] =  20;
    arr2[1] =  1;
    arr2[2] =  18;
    arr2[39] =  39;
   
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
 
    sortA1ByA2(arr1, size1);
 
    for (int i = 0; i < size1; i++)
        printf("%d ", arr1[i]);
    return 0;
}

Output

20 20 1 1 18 18 5 6 7 9 39

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Comments