Wednesday 28 June 2017

Insertion Sort

Start empty handed
Insert  a card in the right postion of the already sorted hand.
Continue until all cards are inserted/sorted.



Integer [] a=new Integer[]{50,11,23,10,20,30,40,10};

Integer n = a.size();
for (Integer i=1; i<n; ++i)
{
    Integer key = a[i];
    Integer j = i-1;

    /* Move elements of a[0..i-1], that are
    greater than key, to one position ahead
    of their current position */
    while (j>=0 && a[j] > key)
    {
        a[j+1] = a[j];
        j = j-1;
    }
    a[j+1] = key;
}

for (Integer i=0; i<n; ++i)
System.debug(a[i] + '  ');




Code in Apex to get Maximum Number from  an Array

                Integer [] a=new Integer[]{10,20,30,40};

                Integer currentMax=a[0];

                for(integer i =1;i<=a.size()-1;i++){
                   if(currentMax<a[i]){
                       currentMax=a[i];
                  }
                }