哪位大神能给我讲一下插入排序,用java程序讲

解决方案 »

  1.   

    东西在注释里已经写清楚了,如果你对这些东西感兴趣,关注下我的博客吧!
    http://blog.csdn.net/zhangerqing
    如有不懂,可以继续问,或者留言!
    package com.xtfggef.algo;/**
     * 直接插入排序 -Java实现 
     * 思路:从待排序的数中选出一个来,插入到 前面的合适位置
     * 
     * @author erqing
     * 
     */
    public class Sort {
    public static void main(String[] args) {
    int data[] = { 8, 22, 78, 29, 1, 67, 99, 56 };
    InsertSort is = new InsertSort();
    is.data = data;
    is.insertSort(data);
    is.dsp();
    }
    }/**
     * 直接插入排序的实现
     * 
     * @author erqing
     * 
     */
    class InsertSort {

    public int data[]; /**
     * tmp表示待插入的数,通过1处的while循环,找出最小的数, 通过2处将tmp插入
     * 
     * @param data
     */
    public void insertSort(int data[]) {
    int i, j, tmp;
    for (i = 1; i < data.length; i++) {
    tmp = data[i];
    j = i - 1;
    while (j >= 0 && tmp < data[j]) {// ----1------
    data[j + 1] = data[j];
    j--;
    }
    data[j + 1] = tmp;// ----2----
    }
    }
    /**
     * 显示排序后的数据
     */
    public void dsp() {
    for (int k = 0; k < data.length; k++) {
    System.out.print(data[k] + " ");
    }
    }
    }
      

  2.   

    怎么最近都是问插入排序的啊,刚回答完一个。再来一次。另外楼主,插入排序的升级是shell排序,性能提升不少,是一种很稳定的排序。推荐楼主看一下
    插入排序算法模板,直接插入排序是在把元素a[i]插入到已经排好序的a[0]—a[i-1]中,时间复杂度最差O(N^2),最好O(N)    /**
         * 直接插入排序
         * @param sortArray
         */
        public static void InsertSort(int[] sortArray){
            
            for(int i=1;i<sortArray.length;i++){
                int compareVale = sortArray[i];
                int j = i;
                while(j>0 && compareVale<sortArray[j-1]){
                    //----->如果compareVale小于sortArray[j],则后退
                    sortArray[j]=sortArray[j-1];
                    j--;
                }
                sortArray[j]=compareVale;
            }  
        }