插入排序

来源:互联网 发布:nes30 pro软件 编辑:程序博客网 时间:2024/06/06 00:20

思想:从第二个数开始,插到前面的有序数列中的合适位置(第一个数视为一个有序数列)。
即如: 1 3 4 6 2 5 -1 
遍历到2时发现 2 < 3,故将2插入3前,即3到6向后移动一位,2放到3三前面
同理5插到6前,-1插到1前


package sort;public class Sort {    public static void main(String[] args) {        int[] a = {1,1,5,4,3,3,-1};        insertSort(a);        for (int i : a) {            System.out.print(i+" ");        }    }           //插入排序    public static void insertSort(int[] arr) {        int size = arr.length;        int temp = 0 ;        int j =  0;            for(int i = 0 ; i < size ; i++){            temp = arr[i];            //假如temp比前面的值小,则将前面的值后移            for(j = i ; j > 0 && temp < arr[j-1] ; j --){                arr[j] = arr[j-1];            }            arr[j] = temp;        }    }        }


原创粉丝点击