-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathinsert_sort.py
73 lines (56 loc) · 1.42 KB
/
insert_sort.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
'''
README
This module aims to introduce the popular sorting method--direct insert sort
and three different kinds of implementation schemes are conducted by python 3 language.
'''
# -*- coding:utf-8 -*-
import math
import copy as cp
class InsertSortMethod():
# construction method
def __init__(self, array):
self.array=array
# the original method that insert the number to the proper position of sorted subset one by one
def insert_sort1(self):
array=cp.deepcopy(self.array)
n=len(array)
for i in range(n-1):
# firstly, array[0] is the sorted subset
if array[i+1]<array[i]:
temp=array[i+1]
j=i;
while j>=0:
if array[j]>temp:
array[j+1]=array[j]
j=j-1
else:
break
array[j+1]=temp
return array
# set a tag when each swapping operation occurs
def insert_sort2(self):
array=self.array[:]
n=len(array)
for i in range(n-1):
# firstly, array[0] is the sorted subset
if array[i+1]<array[i]:
j=i
while j>=0:
if array[j]>array[j+1]:
# swap operation
temp=array[j]
array[j]=array[j+1]
array[j+1]=temp
j=j-1
else:
break
return array
if __name__=='__main__':
testlist=[2,5,7,1,9,4,6,0,12,35,7,3,30]
insert=InsertSortMethod(testlist) # new object of InsertSortMethod class
sortlist=insert.insert_sort1()
print(sortlist)
print(insert.array)
sortlist=insert.insert_sort2()
print(sortlist)
print(insert.array)