码迷,mamicode.com
首页 > 编程语言 > 详细

插入排序 java实现

时间:2016-05-12 12:34:54      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

插入排序也是一种经典的排序方式,适合于已经基本有序,且数据量较小的数组。自己动手写了一个java版本的插入排序。请同学们参考。

package leilei.bit.edu.t2;

public class InsertSort {

    public static void insertSort(int[] a) {
        int arr_length = a.length;
        int j; //当前位置,第j个要确定的位置
        int i; //往前推要比较的位置。
        int value; //当前位置,第j个位置的值

        System.out.print("Before sort, the array is:");
        printArr(a);

        //从第二个位置开始循环比较
        for(j = 1; j < arr_length; j++) {
            value = a[j];
            i = j - 1;
            //如果第i个位置比当前位置的数要大,将第i个位置的数据往后移
            while(i>0 && a[i]>value) {
                a[i+1] = a[i];
                i--;
            }
            //找到当前位置,即第j个位置的值需要插入的具体位置。
            a[i+1] = value;
        }
        System.out.print("After sort , the array is:");
        printArr(a);
    }

    public static void printArr(int[] a) {
        for(int i=0; i<a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] a = {1,5,4,3,8,9,7,6,2};
        insertSort(a);
    }
}

运行的结果:

Before sort, the array is:1 5 4 3 8 9 7 6 2 
After sort , the array is:1 2 3 4 5 6 7 8 9 

具体的思路,其实代码里的注释已经解释得很清楚。等有空了再补个图吧。嘿嘿

插入排序 java实现

标签:

原文地址:http://blog.csdn.net/bitcarmanlee/article/details/51360889

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!