Sort List in Ascending Order
We have two unsorted list, now we want to merge them together into one list and sort them.
l1 = 4,9,3
l2 = 2,7,5
Solution
List<Integer> l1= new List<integer>{4,9,3}; List<Integer> l2= new List<integer>{2,7,5} List<Integer> l3= new List<integer>(); integer temp =0; //add list l1 elements in list l3 for(integer i=0; i<l1.size();i++){ l3.add(l1); } //add list l2 elements in list l3 for(integer i=0; i<l1.size();i++){ l3.add(l2); } //iterate over first element of l3 for(integer i=0; i<l3.size();i++) { //iterate over next element of l3 for(integer j=i+1; j<l3.size();j++){ //if first element is greater than the next element then swap the positions of values if(l3[i]>l3[j]) { //for swapping the values store first element in temp variable temp = l3[i]; //now swap the element l3[i]=l3[j]; //as temp is having first element then put it in next place l3[j]=temp; } } } system.debug('l3 '+l3);
Output
l3 = 4,9,3,2,7,5
Sort List in Descending Order
List<Integer> l3= new List<integer>{4,9,3,2,7,5}; integer temp =0; for(integer i=0; i<l3.size();i++) { for(integer j=i+1; j<l3.size();j++){ if(l3[i]<l3[j]) { temp = l3[i]; l3[i]=l3[j]; l3[j]=temp; } } } system.debug('l3 '+l3);