插入排序算法

1、插入排序算法的介绍

  通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应的位置并插入。

  假定n是数组的长度,首先假设第一个元素被放置在正确的位置上,这样仅需从1-(n-1)范围内对剩余元素进行排序。对于每次遍历,从0-(i-1)范围内的元素已经被排好序,每次遍历的任务是:通过扫描前面已排序的子列表,将位置i处的元素定位到从0到i的子列表之内的正确的位置上。

2、插入排序算法的特点

  • 插入排序算法是一种稳定的排序算法
  • 空间复杂度O(1)
  • 时间复杂度O(n2)
  • 最差情况:当序列出现反序情况的时候,需要移动n*(n-1)/2个元素
  • 最好情况:序列已经有序,不需要移动元素
  • 数组在已排序或者是“近似排序”时,插入排序效率的最好情况运行时间为O(n);
  • 插入排序最坏情况运行时间和平均情况运行时间都为O(n*n)。
  • 通常,插入排序呈现出二次排序算法中的最佳性能。
  • 对于具有较少元素(如n<=15)的列表来说,二次算法十分有效。
  • 在列表已被排序时,插入排序是线性算法O(n)。
  • 在列表“近似排序”时,插入排序仍然是线性算法。在列表的许多元素已位于正确的位置上时,就会出现“近似排序”的条件。
  • 通过使用O(nlog2n)效率的算法(如快速排序)对数组进行部分排序,

3、插入排序算法的代码实现

 1 package com.baozi.paixu;
 2 
 3 /**
 4  * 插入排序算法:
 5  * 将数组分为两部分,前一部分时已经有序的数组,后一部分是无序的,每次都从后边无序数组中取出最前的
 6  * 数据插入到前边有序的数组中,并且保证每次插入之后的数组依然是有序的
 7  *
 8  * @author BaoZi
 9  * @create 2019-05-15-16:09
10  */
11 public class InsertSort {
12     public static void main(String[] args) {
13         final int MAX = 15;
14         int[] nums = new int[MAX];
15         System.out.println("...............使用的是插入排序算法...............");
16         for (int i = 0; i < MAX; i++) {
17             nums[i] = (int) (Math.random() * 10 + 5);
18         }
19         System.out.println("排序之前的数组为...............");
20         for (int i = 0; i < MAX; i++) {
21             System.out.print(nums[i] + " ");
22         }
23         System.out.println();
24         System.out.println("排序之后的数组为...............");
25         //使用选择排序算法进行排序:
26         InsertSort.insertSort(nums);
27         for (int i = 0; i < MAX; i++) {
28             System.out.print(nums[i] + " ");
29         }
30         System.out.println();
31     }
32 
33     public static void insertSort(int[] nums) {
34         //插入排序算法默认的第一个元素直接就是有序的,所以第二个元素开始进行插入排序
35         for (int i = 1; i < nums.length; i++) {
36             int temp_num = nums[i];
37             int temp_index = i - 1;
38             //这个while循环用于找出当前i元素在0---i的准确位置
39             while (temp_num < nums[temp_index]) {
40                 nums[temp_index + 1] = nums[temp_index];
41                 temp_index--;
42                 if (temp_index == -1) {
43                     break;
44                 }
45             }
46             nums[temp_index + 1] = temp_num;
47         }
48     }
49 }

 

posted @ 2019-05-27 16:02  包子的百草园  阅读(292)  评论(0编辑  收藏  举报