插入排序

插入排序
思路:把右侧无序的数据项逐个插入到左侧有序的部分。
如图:
这里写图片描述

插入排序主要代码:

public void insertionSort(){        //插入排序
        int in,out;
        for(out=1;out<nElem;out++){
            long temp=a[out];
            in=out;
            while(in>0&&a[in-1]>=temp){
                a[in]=a[in-1];
                in--;
            }
            a[in]=temp;
        }
    }

插入排序完整代码示例:

package com.swy.sort2;

public class ArrayIns {

    private long[] a;       //定义数组
    private int nElem;      //标记数组长度

    public ArrayIns(int max){   //构造函数
        a=new long[max];
        nElem=0;
    }

    public void display(){          //打印 数组内容
        for(int j=0;j<nElem;j++){
            System.out.print(a[j]+" ");
        }
        System.out.println("");
    }

    public void insert(long value){     //插入方法
        a[nElem]=value;
        nElem++;
    }
    public void insertionSort(){        //插入排序
        int in,out;
        for(out=1;out<nElem;out++){
            long temp=a[out];
            in=out;
            while(in>0&&a[in-1]>=temp){
                a[in]=a[in-1];
                in--;
            }
            a[in]=temp;
        }
    }

}
package com.swy.sort2;

public class InsertSortApp {

    public static void main(String[] args) {
        int maxSize=100;
        ArrayIns arr;
        arr=new ArrayIns(maxSize);

        arr.insert(77);
        arr.insert(55);
        arr.insert(88);
        arr.insert(00);
        arr.insert(33);
        arr.insert(22);

        arr.display();

        arr.insertionSort();

        arr.display();
    }

}

输出:
77 55 88 0 33 22
0 22 33 55 77 88

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值