java

一.原理和思想

有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序。

插入排序的基本思想是:每步将一个待排序的纪录,按其关键码值的大小插入前面已经排序的文件中适当位置上,直到全部插入完为止。

二.示例

三.代码

 1 public class Insertion {
 2     public void insertSort(int[] array){
 3         int temp = 0;
 4         for(int i=1;i<array.length;i++){
 5             //从前两个数开始比较,每趟比较次数逐渐增加
 6             for(int j=i;j>0;j--){
 7                 if(array[j]<array[j-1]){
 8                     temp = array[j];
 9                     array[j] = array[j-1];
10                     array[j-1] = temp;
11                 }else{
12                     break;
13                 }
14             }
15         }
16     }
17     public static void main(String[] args) {
18         Insertion insertion = new Insertion();
19         int[] array = {6,5,4,7,8,9,2,3,4,7};
20         insertion.insertSort(array);
21         for(int i:array){
22             System.out.println(i);
23         }
24     }
25 }
原文地址:https://www.cnblogs.com/fenglanglang/p/5981574.html