答:用插入法进行排序代码如下:
/**
* Created by Felix on 2018/2/18 00:02
* 插入排序
*/
public class InsertSort {
private List<Integer> al;
private 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(Math.abs(rand.nextInt()) % mod + 1);
System.out.println("al[" + i + "]=" + al.get(i));
}
}
private void sortIt() {
int tempInt;
int maxSize = 1;
for (int i = 1; i < al.size(); i++) {
tempInt = al.remove(i);
if (tempInt >= al.get(maxSize - 1)) {
al.add(maxSize, tempInt);
maxSize++;
System.out.println(al.toString());
} else {
for (int j = 0; j < maxSize; j++) {
if (al.get(j) >= tempInt) {
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();
}
}