Files
udemy_algorithms/Sorting Algorithms/Quick Sort.ipynb

110 lines
2.6 KiB
Plaintext
Raw Normal View History

2021-01-30 22:30:06 -08:00
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Quick Sort\n",
"© 2021, Joe James"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {},
"outputs": [],
"source": [
"import random\n",
"\n",
"def quick_sort(A):\n",
" quick(A, 0, len(A)-1)\n",
"\n",
"def quick(A, low, hi):\n",
" if low < hi:\n",
" p = partition(A, low, hi)\n",
" quick(A, low, p-1)\n",
" quick(A, p+1, hi)\n",
"\n",
"def get_pivot(A, low, hi):\n",
" return random.randrange(low, hi+1)\n",
" \n",
"def partition(A, low, hi):\n",
" pivotIndex = get_pivot(A, low, hi)\n",
" pivotValue = A[pivotIndex]\n",
" A[pivotIndex], A[low] = A[low], A[pivotIndex]\n",
" border = low\n",
"\n",
" for i in range(low, hi+1):\n",
" if A[i] < pivotValue:\n",
" border += 1\n",
" A[i], A[border] = A[border], A[i]\n",
" A[low], A[border] = A[border], A[low]\n",
"\n",
" return (border)"
]
},
{
"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": 85,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Success\n"
]
}
],
"source": [
"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' + str(j)\n",
" print(result)\n",
"test(quick_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
}