Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6018cee

Browse files
committed
A simple merge sort implementation
1 parent 139109e commit 6018cee

File tree

1 file changed

+83
-2
lines changed

1 file changed

+83
-2
lines changed

Python/sorting/sorting.ipynb

Lines changed: 83 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,87 @@
11
{
2-
"cells": [],
3-
"metadata": {},
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": 26,
6+
"metadata": {
7+
"collapsed": true
8+
},
9+
"outputs": [],
10+
"source": [
11+
"from math import floor\n",
12+
"from heapq import merge"
13+
]
14+
},
15+
{
16+
"cell_type": "code",
17+
"execution_count": 68,
18+
"metadata": {
19+
"collapsed": true
20+
},
21+
"outputs": [],
22+
"source": [
23+
"\"\"\"\n",
24+
"Merge Sort function.\n",
25+
"1. Uses list operations and merging from heapq to reduce code.\n",
26+
"2. list[start: end + 1] returns part of the list from start to end.\n",
27+
"3. Update a section of list directly by doing list[start: end + 1] = update_list\n",
28+
" (same size)\n",
29+
"\"\"\"\n",
30+
"def mergesort(a, start, end):\n",
31+
" if (start < end):\n",
32+
" mergesort(a, start, floor((start+end)/2))\n",
33+
" mergesort(a, floor((start+end)/2) + 1, end)\n",
34+
" merge_list(a, start, end)\n",
35+
"\n",
36+
"# Merge the lists here.\n",
37+
"def merge_list(a, start, end):\n",
38+
" mid = floor((start+end)/2) + 1\n",
39+
" lst = list(merge(a[start: mid], a[mid: end + 1]))\n",
40+
" a[start: end + 1] = lst\n"
41+
]
42+
},
43+
{
44+
"cell_type": "code",
45+
"execution_count": 71,
46+
"metadata": {
47+
"collapsed": false
48+
},
49+
"outputs": [
50+
{
51+
"name": "stdout",
52+
"output_type": "stream",
53+
"text": [
54+
"[1, 2, 3, 4, 5, 6, 8, 9, 10]\n"
55+
]
56+
}
57+
],
58+
"source": [
59+
"# Testing Sorting functions.\n",
60+
"a = [2, 1, 4, 6, 5, 3, 10, 9, 8]\n",
61+
"mergesort(a, 0, len(a) - 1)\n",
62+
"print(a)"
63+
]
64+
}
65+
],
66+
"metadata": {
67+
"kernelspec": {
68+
"display_name": "Python 3",
69+
"language": "python",
70+
"name": "python3"
71+
},
72+
"language_info": {
73+
"codemirror_mode": {
74+
"name": "ipython",
75+
"version": 3
76+
},
77+
"file_extension": ".py",
78+
"mimetype": "text/x-python",
79+
"name": "python",
80+
"nbconvert_exporter": "python",
81+
"pygments_lexer": "ipython3",
82+
"version": "3.4.3"
83+
}
84+
},
485
"nbformat": 4,
586
"nbformat_minor": 0
687
}

0 commit comments

Comments
 (0)