插入排序案例代码

转载请注明出处:http://blog.csdn.net/droyon/article/details/8780598

/**
 * 插入排序利用到了这样的事实:0到p-1上的元素,全部处于已排序状态。
 * 插入排序没有数据替换,而是用到了数据移动。
 * 位置p上的元素,储存于temp上,p之前所有更大的元素向右移动一个位置,然后temp被置于正确的位置上。
 * 由于嵌套循环,因此插入排序的时间复杂度为O(N的平方	)
 * @author
 *
 */
public class SimpleInsertMethodSort {
	private static int[] array = new int[]{1,8,2,9,3,7,11,23,90,4,5};
	
	public static void main(String args[]){
		System.out.println("排序前");
		printArray();
		simpleInsertSort();
		System.out.println("\n排序后");
		printArray();
	}
	
	public static void simpleInsertSort(){
		for(int p=1;p<array.length;p++){
			int temp;
			temp = array[p];
			int j;
			for(j=p;j>0&&temp<array[j-1];j--){//找到合适的位置,插入元素,并将位置之后的元素后移
				array[j]=array[j-1];
			}
			array[j] = temp;
		}
	}
	
	public static void printArray(){
		for(int i=0;i<array.length;i++){
			System.out.print(array[i]+"   ");
		}
	}
}


运行结果:

排序前
1   8   2   9   3   7   11   23   90   4   5   
排序后
1   2   3   4   5   7   8   9   11   23   90   


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hailushijie

您的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值