111 lines
2.5 KiB
Plaintext
111 lines
2.5 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Merge Sort\n",
|
|
"© 2021, Joe James"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 19,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import sys\n",
|
|
"\n",
|
|
"def merge_sort(A):\n",
|
|
" split(A, 0, len(A)-1)\n",
|
|
" \n",
|
|
"def split(A, first, last):\n",
|
|
" if first < last:\n",
|
|
" middle = (first + last)//2\n",
|
|
" split(A, first, middle)\n",
|
|
" split(A, middle+1, last)\n",
|
|
" merge(A, first, middle, last)\n",
|
|
" \n",
|
|
"def merge(A, first, middle, last):\n",
|
|
" L = A[first:middle+1]\n",
|
|
" R = A[middle+1:last+1]\n",
|
|
" L.append(sys.maxsize)\n",
|
|
" R.append(sys.maxsize)\n",
|
|
" l = r = 0\n",
|
|
" \n",
|
|
" for a in range (first, last+1):\n",
|
|
" if L[l] <= R[r]:\n",
|
|
" A[a] = L[l]\n",
|
|
" l += 1\n",
|
|
" else:\n",
|
|
" A[a] = R[r]\n",
|
|
" r += 1"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Test Function\n",
|
|
"Set a result flag. The j loop is used to perform 1000 test iterations. The next two lines create and shuffle list A of 100 integers. Then A is passed to our sorting function. The sorted result is compared to a sort using Python's sorted function. After 1000 iterations of the test, the result is printed."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 22,
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"Success\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"import random\n",
|
|
"\n",
|
|
"def test(func):\n",
|
|
" result = 'Success'\n",
|
|
" for j in range(1000):\n",
|
|
" A = [k for k in range(100)]\n",
|
|
" random.shuffle(A)\n",
|
|
" func(A)\n",
|
|
" if A != sorted(A):\n",
|
|
" result = 'Failed'\n",
|
|
" print(result)\n",
|
|
"test(merge_sort)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.7.0"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 2
|
|
}
|