程序员社区

插入排序

原理:对于给定的一组记录,初始时假设第一个记录自成一个有序的序列,其余记录为无序序列。接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,直至最后一个记录插入到有序序列为止。

 

InsertSort

package 插入排序;

public class InsertSort {
    public void insertSort(int a[]) {
        if (a != null) {
            for (int i = 1; i < a.length; i++) {
                int temp = a[i];
                int j = i;
                int n = i;
                for(;j>=1;j--){
                    if(a[j-1]>temp){
                        a[j] = a[j-1];
                        n = j-1;
                    }
                }
                a[n] = temp;
            }
        }
    }
}

Test

package 插入排序;

public class Test02 {
public static void main(String[] args) {
    InsertSort insertSort = new InsertSort();
    int a[] = {7,3,19,40,4,7,1};
    insertSort.insertSort(a);
    for (int i = 0; i < a.length; i++) {
        System.out.println(a[i]);
    }
}
}

1
3
4
7
7
19
40

赞(0) 打赏
未经允许不得转载:IDEA激活码 » 插入排序

一个分享Java & Python知识的社区