Tuesday 11 August 2015

Sort an array according to other array

Given two arrays A1 and A2, sort A1 as per the order of elements in A2.

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

Final result is
A1[] = {5, 5, 3, 3, 2, 1, 1, 9, 6, 7, 7}


We can solve this problem by using custom comparator. Instead of comparing elements of A1[], we compare indexes of A1[] elements in A2[].
import java.util.*;

public class SortArray {

 public static void sort(List<Integer> a1, List<Integer> a2) {

  Collections.sort(a1, new Comparator<Integer>() {
   public int compare(Integer data1, Integer data2) {
    int index1 = a2.indexOf(data1);
    int index2 = a2.indexOf(data2);

    if (index1 != -1 && index2 != -1)
     return index1 - index2;
    if (index1 != -1)
     return -1;
    return 1;
   }
  });

 }
}

import java.util.Arrays;
import java.util.List;

public class SortArrayTest {
 public static void main(String args[]){
  List<Integer> a1 = Arrays.asList(1, 2, 3, 9, 5, 6, 7, 1, 3, 5, 7);
  List<Integer> a2 = Arrays.asList(5, 3, 2, 1);
 
  
  SortArray.sort(a1, a2);
  
  System.out.println(a1);
 }
}


Output
[5, 5, 3, 3, 2, 1, 1, 9, 6, 7, 7]


No comments:

Post a Comment