Java面试试题之插入法排序

import javax.print.attribute.standard.MediaSize.Other;

public class Sort {
	public static void main(String[] args) {
		int[] arr = new int[] { 9, 8, 7, 5, 6, 4, 2, 3, 0, 1,11 };
		int[] other = new int[arr.length];
		int count = 1;  // count用来统计新数列中的元素个数
		boolean flag = true;
		other[0] = arr[0];  // 向新数列中先存放一个
		for(int i=1; i<arr.length; i++){
			for(int j=0; j<count; j++){
//				如果arr[i]大于other[j]的话,就继续向后比较,如果不是插入数据,如果比所有的数据都大
				if(arr[i]>other[j] && j!=(count-1)){
					continue;	
				}else if(flag){
					insert(j, other, arr[i]);
					flag = false;			// 如果这里插入成功的话,后面的数据就不用再逐一比较
				}
			}
			flag = true;
			count++;
		}
		print(other);
	}
	
	/**
	 * 插入新数据
	 * @param pos 插入位置
	 * @param other 插入数组
	 * @param value 插入的值
	 */
	public static void insert(int pos, int[] other, int value){
		for(int i=other.length-1; i>pos; i--){
			other[i] = other[i-1];
		}
		other[pos] = value;
	}
	
	/**
	 * 打印数组
	 */
	public static void print(int[] other){
		for(int x=0; x<other.length; x++){
			System.out.println(other[x]);
		}
	}
}

  

转载于:https://www.cnblogs.com/tomastong/p/3810464.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值