Skip to content

Latest commit

 

History

History
144 lines (117 loc) · 3.62 KB

3.insertionSort.md

File metadata and controls

144 lines (117 loc) · 3.62 KB

插入排序

插入排序的代码实现虽然没有冒泡排序和选择排序那么简单粗暴,但它的原理应该是最容易理解的了,因为只要打过扑克牌的人都应该能够秒懂。插入排序是一种最简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

插入排序和冒泡排序一样,也有一种优化算法,叫做拆半插入。

1. 算法步骤

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

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

2. 动图演示

动图演示

3. JavaScript 代码实现

functioninsertionSort(arr){varlen=arr.length;varpreIndex,current;for(vari=1;i<len;i++){preIndex=i-1;current=arr[i];while(preIndex>=0&&arr[preIndex]>current){arr[preIndex+1]=arr[preIndex];preIndex--;}arr[preIndex+1]=current;}returnarr;}

4. Python 代码实现

definsertionSort(arr): foriinrange(len(arr)): preIndex=i-1current=arr[i] whilepreIndex>=0andarr[preIndex] >current: arr[preIndex+1] =arr[preIndex] preIndex-=1arr[preIndex+1] =current    returnarr

5. Go 代码实现

funcinsertionSort(arr []int) []int { fori:=rangearr { preIndex:=i-1current:=arr[i] forpreIndex>=0&&arr[preIndex] >current { arr[preIndex+1] =arr[preIndex] preIndex-=1 } arr[preIndex+1] =current } returnarr }

6. Java 代码实现

publicclassInsertSortimplementsIArraySort { @Overridepublicint[] sort(int[] sourceArray) throwsException { // 对 arr 进行拷贝,不改变参数内容int[] arr = Arrays.copyOf(sourceArray, sourceArray.length); // 从下标为1的元素开始选择合适的位置插入,因为下标为0的只有一个元素,默认是有序的for (inti = 1; i < arr.length; i++) { // 记录要插入的数据inttmp = arr[i]; // 从已经排序的序列最右边的开始比较,找到比其小的数intj = i; while (j > 0 && tmp < arr[j - 1]) { arr[j] = arr[j - 1]; j--; } // 存在比其小的数,插入if (j != i) { arr[j] = tmp; } } returnarr; } }

7. PHP 代码实现

functioninsertionSort($arr) { $len = count($arr); for ($i = 1; $i < $len; $i++) { $preIndex = $i - 1; $current = $arr[$i]; while($preIndex >= 0 && $arr[$preIndex] > $current) { $arr[$preIndex+1] = $arr[$preIndex]; $preIndex--; } $arr[$preIndex+1] = $current; } return$arr; }

8. C 代码实现

voidinsert_sort(intdata[], intn) { inti,j; inttemp; for(i=1;i<n;i++) { temp=data[i]; j=i-1; //与已排序的数逐一比较,大于temp时,该数移后while((j>=0)&&(data[j]>temp)) { data[j+1]=data[j]; j--; } //存在大于temp的数if(j!=i-1) data[j+1]=temp; } }
close