十大经典排序算法(三、插入排序)

动图演示

算法步骤

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

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

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 }

 

posted @ 2020-12-29 11:37  梓涵VV  阅读(81)  评论(0编辑  收藏  举报