Tuesday, July 23, 2013

How to Sort List programatically without using any in built functions in Java


   // Sort list of integers in descending order.
    private static List<Integer> sortList(List<Integer> pList){
        int temp;
        if(pList != null && pList.size() > 0){
            for(int i=0;i<pList.size();i++){
                for(int j=i+1;j<pList.size();j++){
                    if(pList.get(j) > pList.get(i)){
                        temp = pList.get(i);
                        pList.set(i,pList.get(j));
                        pList.set(j,temp);
                    }
                }
            }
        }
        return pList;
    }

Test

// Initialize and assign values
List<Integer> list1 =Arrays.asList(2,5,23,-1,-5,0,4);
// Invoke above sortList() method.


- How to merge two lists in a sorted order ?

// Initialize & assign two lists
List<Integer> list1 =Arrays.asList(2,5,23,-1,-5,0,4);
List<Integer> list2 =Arrays.asList(23,15,323,-51,-65,0,47);
 
// Add the second list to first list
list1.addAll(list2);
// Invoke above sortList() method by passing merged list i.e list1.

No comments:

Post a Comment