Saturday, August 9, 2014

Given an array of integers. This array denotes ‘our’ own ascending order of the elements. So if the array is {2,3,1,4}, by mathematics we can say that 2<3<1<4. Given another array, sort this new array in ‘our’ ascending order.
Let’s say the new array is {1,2,4,3,5,4,9,2}, output will be {2,2,3,1,4,4,5,9}. Note that since 5 and 9 do not occur, they are sorted by actual ascending order at the end.



import java.util.*;

/**
 * Created by Arun on 8/9/14.
 */
public class CustomizedSort {
    public static ArrayList<Integer> sort(int customSortList[], Integer arr[]){
        Map<Integer, Integer> mp = new LinkedHashMap<Integer, Integer>();
        for(int i=0;i<customSortList.length;i++) {
            mp.put(customSortList[i], i);
        }
        System.out.println(mp);
        List<Integer> a = Arrays.asList(arr);
        Collections.sort(a);
        arr = a.toArray(new Integer[arr.length]);
        ArrayList<Integer> newArr = new ArrayList<Integer> (arr.length);

        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry pairs = (Map.Entry)it.next();
            int key = (Integer)pairs.getKey();
            for(int i=0;i<a.size();i++){
                if(a.get(i)==key){
                    newArr.add(key);
                }
            }
        }
        for(int i=0;i<a.size();i++){
            if (!newArr.contains(a.get(i))){
                newArr.add(a.get(i));
            }
        }
        return newArr;
    }
    public static void main(String args[]){
        int customSortList[] = {2,3,1,4};
        Integer arr [] = {1,2,4,3,5,4,9,2};
        System.out.println(sort(customSortList, arr));
    }
}

No comments:

Post a Comment