zoukankan      html  css  js  c++  java
  • 排序算法之直接插入排序

    概念

    从第2个元素开始,将每一个元素插入到已经排好序的序列中,得到一个新的排好序的序列

    Java版实现

    	public static void insert(Integer[] array) {
    		Integer s;
    		int j;
    		for (int i = 1; i < array.length; i++) {
    			if (array[i] < array[i-1]) {
    				s = array[i];
    				for (j = i-1; j >= 0 && array[j] > s; j--)
    					array[j+1] = array[j]; // move the element backward
    				array[j+1] = s; // put the ith element in the right place
    			} // end if the element i-1 larger than element i
    		} // end for loop and compare length-1 times
    	}
    

    时间复杂度分析

    最差情况,初始为倒序序列,需要比较的次数为(n-1)(n+2)/2次,需要移动(n+4)(n-1)/2次,时间复杂度为O(n2)

    最好情况,初始为已排序序列,需要比较的次数为n-1次,需要移动0次,时间复杂度为O(n)

    与冒泡和简单选择排序比较,个人觉得并没有体现优势

    空间复杂度分析

    需要的辅助空间为O(1)

  • 相关阅读:
    [C#] override和overload的区别
    [ASP.Net] 20141228_Dapper文章搜集
    JSP
    Ajax使用简介
    编写JAVA脚本的JSP页面
    JAVA web开发模式
    JSP基础
    过滤器
    监听会话范围内事件
    http解析
  • 原文地址:https://www.cnblogs.com/scarlettxu/p/3488411.html
Copyright © 2011-2022 走看看