-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort-insertion.py
More file actions
35 lines (30 loc) · 865 Bytes
/
sort-insertion.py
File metadata and controls
35 lines (30 loc) · 865 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import numpy as np
def insertion_sort(dat,desc = False):
"""
This functions support the sorting method - insertion.
Parameters
----------
dat : a list, or tuple or numpy array
desc : optional, specify the order style, ascend or descend
Returns
-------
A sorted list, tuple or numpy array.
If the type is not correct, the dat will be returned as no changed.
"""
if not isinstance(dat,(tuple,list,np.ndarray)):
return dat
length = len(dat)
for i in range(1,length):
tmp = dat[i]
j = i-1
if desc:
while j>=0 and dat[j] <tmp:
dat[j+1] = dat[j]
j-=1
dat[j+1] = tmp
else:
while j>=0 and dat[j] >tmp:
dat[j+1] = dat[j]
j-=1
dat[j+1] = tmp
return dat