算法中插入法很经典,先和大家分享一下:
public class SortAlgorithm2 {
public void insertSortAsc(int[] numlist) {// 插入法升序排列
int out, in;
for (out = 1; out < numlist.length; out++) {
int temp = numlist[out];
in = out;
while (in > 0 && numlist[in - 1] > temp) {
numlist[in] = numlist[in - 1];
in--;
}
numlist[in] = temp;
}
}
public void insertSortDes(int[] numlist) {// 插入法降序排列
int out, in;
for (out = 1; out < numlist.length; out++) {
int temp = numlist[out];
in = out;
while (in > 0 && numlist[in - 1] < temp) {
numlist[in] = numlist[in - 1];
in--;
}
numlist[in] = temp;
}
}
public static void main(String[] args) {
SortAlgorithm2 demo = new SortAlgorithm2();
int[] num = { 12, 35, 13, 46, 24, 44, 23 };
System.out.println("-----insertSortAcs-------");
demo.insertSortAsc(num);
for (int i : num)
System.out.print(new Integer(i).toString() + "/t");
System.out.println();
System.out.println("-------insertSortDes-------");
demo.insertSortDes(num);
for (int i : num)
System.out.print(new Integer(i).toString() + "/t");
}
}
运行结果如下:
-----insertSortAcs-------
12 13 23 24 35 44 46
-------insertSortDes-------
46 44 35 24 23 13 12