第四课 插入排序

[quote]笔记--插入排序[/quote]
[b]1.插入排序类[/b]

package com.flysnow.chap03;

/**
* 插入排序
* @author 飞雪无情
* @since:2010-3-25
*/
public class ArrayInsert {
private long[] a;
private int nElems;
public ArrayInsert(int max){
a=new long[max];
nElems=0;
}
/**
* 插入元素
* @param value
*/
public void insert(long value){
a[nElems]=value;
nElems++;
}
/**
* 打印元素
*/
public void display(){
for(int i=0;i<nElems;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
/**
* 插入排序排序
*/
public void insertionSort(){//比较次数O(N^2),但是复制比交换的时间要少。比冒泡快一倍,比插入略快
int out,in;
for(out=0;out<nElems;out++){
long temp=a[out];//标记
in=out;
while(in>0&&a[in-1]>=temp){//大于标记值右移
a[in]=a[in-1];
--in;
}
a[in]=temp;
}
}
}


[b]2.插入排序测试[/b]
package com.flysnow.chap03;

import java.util.Random;

/**
* 插入排序测试
* @author 飞雪无情
* @since:2010-3-25
*/
public class InsertSortApp {
public static void main(String[] args){
ArrayInsert insert=new ArrayInsert(100);
Random random=new Random();
for(int i=0;i<20;i++){//添加20个随机数
insert.insert((long)(random.nextFloat()*100));
}
insert.display();//未排序
insert.insertionSort();//排序
insert.display();//排序后
}
}

[b]3.总结[/b]
算法思想:
[list]
[*]选择第二个(1号)数据为标记,和其前面的数据(0号)比较,如果1号数据小于0,则0号后移变成1号,而原来的1号数据占据原来的0号位置。
[*]选择第三个(2号)数据位标记,和其前面的数据(0号,1号)循环比较,如果前面的数据比标记大,则该数据后移。
[*]依次类推,直到完成排序。。循环条件就是下标大于0并且前面的数据大于等于标记值。
[/list]

[img]http://dl.iteye.com/upload/attachment/226987/171c7cc6-fa98-3cda-a290-2938d9f9055b.bmp[/img]

[img]http://dl.iteye.com/upload/attachment/226989/61d3796e-a8a4-311e-a4c6-0d8790d0295c.bmp[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值