Insertion Sort
Start empty handedInsert 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] + ' ');
No comments:
Post a Comment