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

## Sort an array according to the order defined by another array

Here we will learn about how to sort an array according  to order of another array. 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. ## Algorithm

• Input 3 arrays, array X , array Y and array Z.
• Traverse the elements of array Y from i = 0 to length-1(array Y).
• Check if array X contains the ith element of array Y
• Print all the ith elements.
• Go to step 2 until all the elements of array Y have been traversed.
• If there are any remaining elements in array X, print those elements also.
•  Add all the element in 3rd array. i.e. array Z
• Display array Z.

## C Code

`#include<stdio.h>int main (){  arrayX =  {2, 3, 5, 9, 5, 3, 2, 2, 2, 3, 3, 5, 9};  int arrayY = { 5, 9, 3, 2 };  int i;  int j;  int arrayZ;  int k = 0;  for (i = 0; i < 4; i++)    {      for (j = 0; j < 13; j++)	{	  if (arrayX[j] == arrayY[i])	    {	      arrayZ[k] = arrayX[j];	      k++;	    }	}    }  for (k = 0; k < 13; k++)    {      printf ("\n %d" , arrayZ[k]);    }  return 0;}`
`Output:5559933332222`