Relative Sort

By   Tewodros   Date Posted: Feb. 22, 2022  Hits: 766   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given two list of integers L1 and L2, we want to sort the numbers in L1 in the order as they appear in L2. In addition to that we also want to sort the remaining items on L1 in ascending order.

Example

Input: L1= [3,1,3,4,6,7,9,19], L2= [1,4,3,9,6]

Output: [1,4,3,3,9,6,7,19]

  public int[] RelativeSortArray(int[] arr1, int[] arr2) {       

       Array.Sort(arr1);

       int [] result = new int[arr1.Length];     

       int k = 0, l = 0;

       for(int i=0; i < arr2.Length; i++)       {

           for(int j=0; j < arr1.Length; j++)           {

               if(arr1[j] ==  arr2[i])               {

                   result [k] = arr1[j];

                   k++;

               }                 

           }

       }

       

       Hashtable ht = new Hashtable();

       foreach(int x in arr2)       {

           if(!ht.ContainsKey(x))           {

               ht[x] = x;

           }

       }

       

         int t=0;

         foreach(int x in arr1)         {

              if(!ht.ContainsKey(x))              {

                  result[k] = x;

                  k++;

              }

         }          

       return result;       

   }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* mhwehp

Back to Top