码迷,mamicode.com
首页 > 编程语言 > 详细

Java面试试题之插入法排序

时间:2014-06-27 14:12:19      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:class   blog   java   数据   string   os   

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]);
		}
	}
}

  

Java面试试题之插入法排序,布布扣,bubuko.com

Java面试试题之插入法排序

标签:class   blog   java   数据   string   os   

原文地址:http://www.cnblogs.com/tomastong/p/3810464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!