面试题-用插入法进行排序代码

Android程序员面试宝典

代码如下:

public 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();
    }



}

打印结果:

The ArrayList Sort Before:
al[0]=34
al[1]=14
al[2]=50
al[3]=48
al[4]=2
al[5]=100
al[6]=54
al[7]=15
al[8]=29
al[9]=81
[14, 34, 50, 48, 2, 100, 54, 15, 29, 81]
[14, 34, 50, 48, 2, 100, 54, 15, 29, 81]
[14, 34, 48, 50, 2, 100, 54, 15, 29, 81]
[2, 14, 34, 48, 50, 100, 54, 15, 29, 81]
[2, 14, 34, 48, 50, 100, 54, 15, 29, 81]
[2, 14, 34, 48, 50, 54, 100, 15, 29, 81]
[2, 14, 15, 34, 48, 50, 54, 100, 29, 81]
[2, 14, 15, 29, 34, 48, 50, 54, 100, 81]
[2, 14, 15, 29, 34, 48, 50, 54, 81, 100]
The ArrayList Sort After:
al[0]=2
al[1]=14
al[2]=15
al[3]=29
al[4]=34
al[5]=48
al[6]=50
al[7]=54
al[8]=81
al[9]=100

你可能感兴趣的:(面试题-用插入法进行排序代码)