插入排序

来源:互联网 发布:构造方法 java 编辑:程序博客网 时间:2024/06/03 10:15

插入排序算法思想:

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

代码:

public class InsertSort {    public static void insert(int[] num){        if(num != null){            for (int i = 1; i < num.length; i++) {                int temp = num[i];                int j = i;                if(num[j - 1] > temp){                    while(num[j - 1] > temp && j >= 1){                        num[j] = num[j -1];                        j--;                    }                }                num[j] = temp;            }        }    }    public static void main(String[] args) {        int[] arr = {2,5,3,1,7,6,4};        insert(arr);        for (int i = 0; i < arr.length; i++) {            System.out.print(arr[i] + " ");        }    }}
0 0
原创粉丝点击