zoukankan      html  css  js  c++  java
  • 十大经典排序算法(三、插入排序)

    动图演示

    算法步骤

    将待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。

    从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。(如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。)

    JavaScript

     1 function insertionSort(arr) {
     2     var len = arr.length;
     3     var preIndex, current;
     4     for (var i = 1; i < len; i++) {
     5         preIndex = i - 1;
     6         current = arr[i];
     7         while(preIndex >= 0 && arr[preIndex] > current) {
     8             arr[preIndex+1] = arr[preIndex];
     9             preIndex--;
    10         }
    11         arr[preIndex+1] = current;
    12     }
    13     return arr;
    14 }

    Python

    1 def insertionSort(arr):
    2     for i in range(len(arr)):
    3         preIndex = i-1
    4         current = arr[i]
    5         while preIndex >= 0 and arr[preIndex] > current:
    6             arr[preIndex+1] = arr[preIndex]
    7             preIndex-=1
    8         arr[preIndex+1] = current
    9     return arr

    C语言

     1 void insertion_sort(int arr[], int len){
     2         int i,j,key;
     3         for (i=1;i<len;i++){
     4                 key = arr[i];
     5                 j=i-1;
     6                 while((j>=0) && (arr[j]>key)) {
     7                         arr[j+1] = arr[j];
     8                         j--;
     9                 }
    10                 arr[j+1] = key;
    11         }
    12 }

    C++

     1 void insertion_sort(int arr[],int len){
     2         for(int i=1;i<len;i++){
     3                 int key=arr[i];
     4                 int j=i-1;
     5                 while((j>=0) && (key<arr[j])){
     6                         arr[j+1]=arr[j];
     7                         j--;
     8                 }
     9                 arr[j+1]=key;
    10         }
    11 }
  • 相关阅读:
    8086 CPU 寄存器
    python中 * 的用法
    字典的相应操作
    tesseract学习记录
    C学习之路2012.8.28
    函数库管理
    2013.3.19C++浏览记录。。。
    自动生成makefile文件学习
    整理做过的东西(电子警察)
    基于zed的tesseract移植过程记录
  • 原文地址:https://www.cnblogs.com/wangchaoguo-li/p/14205684.html
Copyright © 2011-2022 走看看