Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 8f50689

Browse files
committedMay 22, 2019
learn insertion_sort
1 parent ddf8273 commit 8f50689

File tree

5 files changed

+49
-0
lines changed

5 files changed

+49
-0
lines changed
 
Loading
Loading
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Created by imoyao at 2019/5/13 18:33
4+
5+
import pathlib
6+
import sys
7+
8+
util_p = pathlib.Path('../..').resolve()
9+
10+
sys.path.append(str(util_p))
11+
from util import utils
12+
13+
14+
def insertion_sort(unsorted_collection):
15+
"""
16+
插入排序
17+
从未排序序列中,拿出一个元素,与已经排序的序列比较,对于有序序列中大于该元素的元素,则后移一位腾出空间,其他不变,直到整个序列循环完成
18+
:param unsorted_collection:待排序序列
19+
:return:排序后序列
20+
"""
21+
length = len(unsorted_collection)
22+
for index in range(1, length):
23+
while index > 0 and unsorted_collection[index - 1] > unsorted_collection[index]: # 前一个元素大于后一个元素
24+
unsorted_collection[index], unsorted_collection[index - 1] = unsorted_collection[index - 1], \
25+
unsorted_collection[index]
26+
index -= 1 # 只保持前面已经排列的有序,这点和冒泡相反,冒泡每次排序都保证末端有序
27+
return unsorted_collection
28+
29+
30+
if __name__ == '__main__':
31+
unsorted_li = utils.rand_list(100)
32+
print('Before sorted:', unsorted_li)
33+
print('After sorted:', insertion_sort(unsorted_li))

‎sorts/insertion_sort/readme.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# 插入排序
2+
3+
## 概念
4+
5+
插入排序(Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用`in-place`排序(即只需用到 `O(1)` 的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
6+
7+
## 图示
8+
9+
![插入排序算法](./img/Insertion_sort_animation.gif)
10+
11+
![插入排序实例](./img/Insertion-sort-example.gif)
12+
13+
## 复杂度
14+
15+
平均时间复杂度:`O(n^2)`

‎sorts/readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
- [选择排序](./selection_sort)
66
- [快速排序](./quick_sort)
77
- [冒泡排序](./bubble_sort)
8+
- [插入排序](./insertion_sort)
89

910

1011

0 commit comments

Comments
 (0)
Please sign in to comment.