算法实现Java之插入排序

来源:互联网 发布:我的世界0.15.1枪械js 编辑:程序博客网 时间:2024/06/07 17:49
package com.gpf.arithmetic;public class InsertSort {//前面的数是排序好的,然后后面的数插入到排序好的树中的适当位置public static void main(String[] args) {int [] a = {12,2545,78,2,0,-98,-79,11};insertSort(a);for (int i : a) {System.out.println(i + "  ");}}private static void insertSort(int[] a) {//初始状态,第一个数默认是排序好的for(int i = 1; i < a.length; i++){int temp = a[i];//因为数组要后移,可能覆盖,所以需要把此位置的数值保存下来if(a[i]<a[i-1]){//如果要插入的数比最大的数还大,不需要改变 只需要考虑要插入的数小于已排好序的最大数//寻找最适合的位置int j;for(j = i-1; j>=0&&a[j]>temp; j--){//未找到,则数组后移a[j+1] = a[j];}//跳出循环 把值放入此位置a[j+1] = temp;}}}}