/
sorting.ipynb
273 lines (273 loc) · 8.96 KB
/
sorting.ipynb
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Basic Sorting"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Selection Sort\n",
"For each position i from index 0 to len, search and find the minimum element in the rest of the list and if it is smaller with the element in current position i, swap them.\n",
"\n",
"<img src=\"Graphics/selection.png\" width=\"50%\" align=\"left\">"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [],
"source": [
"def selection_sort(alist):\n",
" size = len(alist)\n",
" count=0 # inner loop counter, only useful to assess performance\n",
" print alist\n",
" for i in range(size-1): # for each position in the list \n",
" # i is your current item. Watch the limit, see notes\n",
" min_item=alist[i] # set the minimum item to be the first item of the iteration\n",
" position=i # mark its position\n",
" for j in range(i+1, size, 1): # search the list for the minimum remaining item, \n",
" # beginning one item to the right of the external loop\n",
" count+=1\n",
" if alist[j]<min_item: \n",
" min_item=alist[j] # mark the new minimum\n",
" position=j # and its position\n",
" if alist[position]<alist[i]: # if the new minimum if smaller than the external loop's current item, swap them\n",
" alist[position], alist[i] = alist[i], alist[position]\n",
" print alist\n",
" print count, \"inner loop iterations\"\n",
" return alist"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Notes: \n",
"In the visualisation above, the four steps correspond to the outer loop indexed `i`. The arrows that locate the minimum item in each step, correspond to the inner loop, indexed `j`.\n",
"\n",
"For a list of 5 items, `i` will start from 0 and will go up to 3 (not 4). This is why the outer loop goes up to `size-1` (with `in range(size==5)`, Python would get you up to 4). When the outer loop `i=1`, the inner loop will check items `j=2` to `j=4`. The inner loop always remains to the right of `i`. For this, for a 5 items list, `i` needs to go up to 3, to avoid a comparison of item at 4 with itself (which may cause unwanted swaps)."
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [],
"source": [
"alist=[10,7,8,3,8,9,5,2,1]"
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[10, 7, 8, 3, 8, 9, 5, 2, 1]\n",
"[1, 7, 8, 3, 8, 9, 5, 2, 10]\n",
"[1, 2, 8, 3, 8, 9, 5, 7, 10]\n",
"[1, 2, 3, 8, 8, 9, 5, 7, 10]\n",
"[1, 2, 3, 5, 8, 9, 8, 7, 10]\n",
"[1, 2, 3, 5, 7, 9, 8, 8, 10]\n",
"[1, 2, 3, 5, 7, 8, 9, 8, 10]\n",
"[1, 2, 3, 5, 7, 8, 8, 9, 10]\n",
"[1, 2, 3, 5, 7, 8, 8, 9, 10]\n",
"36 inner loop iterations\n",
"Sorted:\n",
"[1, 2, 3, 5, 7, 8, 8, 9, 10]\n"
]
}
],
"source": [
"sort = selection_sort(alist)\n",
"print \"Sorted:\"\n",
"print sort"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Insertion Sort\n",
"The sorted part of the list increases from left to right (like in selection) by going through the list and inserting the first element of the unsorted part into into the right position of the sorted part. This is better than selection because you don't have to search the entire remaining list for the minimum item.\n",
"\n",
"<img src=\"Graphics/insertion.png\" width=\"30%\" align=\"left\">"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {},
"outputs": [],
"source": [
"def insertion_sort(alist):\n",
" size = len(alist)\n",
" count=0\n",
" print alist\n",
" for i in range(0, size-1, +1):\n",
" position=i+1 # the position of the item to move: one to the right of the sorted part of the list\n",
" item_to_insert = alist[position]\n",
" j = position # j will iterate in reverse (see why in the notes) on the sorted part, \n",
" # in order to locate the right position\n",
" while alist[j-1]>item_to_insert and j>0:\n",
" count+=1\n",
" j-=1\n",
" # pop the item to move (pop() gets it and removes it from the list)\n",
" # and insert it in the place that j found\n",
" if item_to_insert<alist[j]: alist.insert(j, alist.pop(position))\n",
" print alist\n",
" print count, \"inner loop iterations\"\n",
" return alist"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Notes:\n",
"\n",
"In the visualisation above the sorted list on the left increases with the outer loop index `i`. The arrows depict the insertion of the `i+1` into the correct position in the sorted list, by iterating on the sorted part with index `j`.\n",
"\n",
"Importantly, note that the inner loop is executed in reverse. This way, the closer an input list is to being sorted, the less operations are needed if you start searching for the right position from a position close to each nodes position. This implementation detail guarantees that insertion sort performs better the closer an input list is to being sorted."
]
},
{
"cell_type": "code",
"execution_count": 91,
"metadata": {},
"outputs": [],
"source": [
"alist=[10,7,8,3,8,9,5,2,1]"
]
},
{
"cell_type": "code",
"execution_count": 92,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[10, 7, 8, 3, 8, 9, 5, 2, 1]\n",
"[7, 10, 8, 3, 8, 9, 5, 2, 1]\n",
"[7, 8, 10, 3, 8, 9, 5, 2, 1]\n",
"[3, 7, 8, 10, 8, 9, 5, 2, 1]\n",
"[3, 7, 8, 8, 10, 9, 5, 2, 1]\n",
"[3, 7, 8, 8, 9, 10, 5, 2, 1]\n",
"[3, 5, 7, 8, 8, 9, 10, 2, 1]\n",
"[2, 3, 5, 7, 8, 8, 9, 10, 1]\n",
"[1, 2, 3, 5, 7, 8, 8, 9, 10]\n",
"27 inner loop iterations\n",
"Sorted:\n",
"[1, 2, 3, 5, 7, 8, 8, 9, 10]\n"
]
}
],
"source": [
"sort = insertion_sort(alist)\n",
"print \"Sorted:\"\n",
"print sort"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Comparison and Conclusion\n",
"Both algorithms are **`O(N^2)`** worst case and average. Insertion sort performs better the closer an input list is to being sorted. At the extreme that the input list is already sorted, insertion sort becomes **`O(n)`**. Here is the reason: The outer loop executes the same way for both algorithms. However, insertion sort needs only to span as many items as needed in order to find the right position (none, if the input list is already sorted, in which case the complexity relaxes to `O(n)` due to the outer loop), while selection sort needs always span the entire remaining list to locate the next minimum item."
]
},
{
"cell_type": "code",
"execution_count": 93,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"36 inner loop iterations\n"
]
}
],
"source": [
"a=[1,2,3,4,5,6,7,8,9]\n",
"sort=selection_sort(a)"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"0 inner loop iterations\n"
]
}
],
"source": [
"a=[1,2,3,4,5,6,7,8,9]\n",
"sort=insertion_sort(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.15"
}
},
"nbformat": 4,
"nbformat_minor": 2
}