Import java. util .*;
Class InsertSort
{
ArrayList al;
Public InsertSort (int num, int mod)
{
Al = new ArrayList (num );
Random rand = new Random ();
System. out. println ("The ArrayList Sort Before :");
For (int I = 0; I <num; I ++)
{
Al. add (new Integer (Math. abs (rand. nextInt () % mod + 1 ));
System. out. println ("al [" + I + "] =" + al. get (I ));
}
}
Public void SortIt ()
{
Integer tempInt;
Int MaxSize = 1;
For (int I = 1; I <al. size (); I ++)
{
TempInt = (Integer) al. remove (I );
If (tempInt. intValue ()> = (Integer) al. get (MaxSize-1). intValue ())
{
Al. add (MaxSize, tempInt );
MaxSize ++;
System. out. println (al. toString ());
} Else {
For (int j = 0; j <MaxSize; j ++)
{
If
(Integer) al. get (j). intValue ()> = tempInt. intValue ())
{
Al. add (j, tempInt );
MaxSize ++;
System. out. println (al. toString ());
Break;
}
}
}
}
System. out. println ("The ArrayList Sort After :");
For (int I = 0; I <al. size (); I ++)
{
System. out. println ("al [" + I + "] =" + al. get (I ));
}
}
Public static void main (String [] args)
{
InsertSort is = new InsertSort (10,100 );
Is. SortIt ();
}
}
Aaron @ aaron-ubuntu :~ /Study $ javac InsertSort. java-Xlint: unchecked
Aaron @ aaron-ubuntu :~ /Study $ java InsertSort
The ArrayList Sort Before:
Al [0] = 45
Al [1] = 20
Al [2] = 79
Al [3] = 53
Al [4] = 15
Al [5] = 41
Al [6] = 2
Al [7] = 59
Al [8] = 98
Al [9] = 60
[20, 45, 79, 53, 15, 41, 2, 59, 98, 60]
[20, 45, 79, 53, 15, 41, 2, 59, 98, 60]
[20, 45, 53, 79, 15, 41, 2, 59, 98, 60]
[15, 20, 45, 53, 79, 41, 2, 59, 98, 60]
[15, 20, 41, 45, 53, 79, 2, 59, 98, 60]
[2, 15, 20, 41, 45, 53, 79, 59, 98, 60]
[2, 15, 20, 41, 45, 53, 59, 79, 98, 60]
[2, 15, 20, 41, 45, 53, 59, 79, 98, 60]
[2, 15, 20, 41, 45, 53, 59, 60, 79, 98]
The ArrayList Sort After:
Al [0] = 2
Al [1] = 15
Al [2] = 20
Al [3] = 41
Al [4] = 45
Al [5] = 53
Al [6] = 59
Al [7] = 60
Al [8] = 79
Al [9] = 98