八大排序法之直接插入排序法

本文借鉴 http://blog.csdn.net/without0815/article/details/7697916

1、基本思想

将要插入的元素从后往前插入到已经排好序的序列中。

(1)将待插入元素设为temp

(2)将其与之前的元素比较,若小于上一个元素,则将上一个元素向后移动一位,将带插入元素插入到上一个元素位置,重复

2、Java实现

public static int[] insertSort(int[] numbers)
	{
		int size = numbers.length;
		int temp = 0 ;
		int j =  0;

		for(int i = 0 ; i < size ; i++)
		{
			temp = numbers[i];
			//假如temp比前面的值小,则将前面的值后移
			for(j = i ; j > 0 && temp < numbers[j-1] ; j --)//从小到大
//		    for(j = i ; j > 0 && temp > numbers[j-1] ; j --) 从大到小
			{
				numbers[j] = numbers[j-1];
			}
			numbers[j] = temp;
		}
		return numbers;
	}



	public static void main(String[] args) {
		int []arrays={51,1,32,45,10};
		int []result=insertSort(arrays);
		for(int i=0;i<arrays.length;i++){
			System.out.println(result[i]);
		}
	}


猜你喜欢

转载自blog.csdn.net/qq_34621771/article/details/75315342