Files
udemy_algorithms/Sorting Algorithms/Selection Sort.ipynb
2021-01-30 22:30:06 -08:00

93 lines
2.1 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Selection Sort\n",
"© 2021, Joe James"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"def selection_sort(A):\n",
" for i in range (0, len(A) - 1):\n",
" minIndex = i\n",
" for j in range (i+1, len(A)):\n",
" if A[j] < A[minIndex]:\n",
" minIndex = j\n",
" if minIndex != i:\n",
" A[i], A[minIndex] = A[minIndex], A[i]"
]
},
{
"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": 10,
"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(selection_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
}