插入排序

概述

递增方式插入排序

代码

package com.lilei.myes.es.pack1114;

import java.util.Random;

public class insert_sort {

	public static void main(String[] args) {

		Random rand = new Random();
		
		int[] array = new int[10];
		
		for(int i=0;i<array.length;i++)
			array[i] = rand.nextInt(100);
		
		for(int v:array)
			System.out.print(v+",");
		
		System.out.println();
		
		sort(array);
		
		for(int v:array)
			System.out.print(v+",");
		
	}

	static void sort(int[] array) {

		for (int i = 1; i < array.length; i++) {

			int p = i - 1;
			int value = array[i];

			while (p >= 0 && value < array[p])
			{
				array[p+1] = array[p];
				p--;
			}
			
			if (p != i-1)
				array[p+1] = value;

		}

	}

}

  

posted on 2017-11-14 15:12  李雷  阅读(122)  评论(0编辑  收藏  举报

导航