Skip to content

Commit 416576f

Browse files
committed
add search-algorithms
1 parent a38f179 commit 416576f

1 file changed

Lines changed: 132 additions & 0 deletions

File tree

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Linear Search"
8+
]
9+
},
10+
{
11+
"cell_type": "code",
12+
"execution_count": null,
13+
"metadata": {},
14+
"outputs": [],
15+
"source": [
16+
"list_ = [2, 13, 6, 5, 125]"
17+
]
18+
},
19+
{
20+
"cell_type": "code",
21+
"execution_count": null,
22+
"metadata": {},
23+
"outputs": [],
24+
"source": [
25+
"def linear_search(list_, k):\n",
26+
" \n",
27+
" for i in list_:\n",
28+
" if k == i:\n",
29+
" return \"Found\"\n",
30+
" else:\n",
31+
" return \"Not Found\""
32+
]
33+
},
34+
{
35+
"cell_type": "code",
36+
"execution_count": null,
37+
"metadata": {},
38+
"outputs": [],
39+
"source": [
40+
"linear_search(list_, 2)"
41+
]
42+
},
43+
{
44+
"cell_type": "markdown",
45+
"metadata": {},
46+
"source": [
47+
"# Binary Search"
48+
]
49+
},
50+
{
51+
"cell_type": "code",
52+
"execution_count": 2,
53+
"metadata": {},
54+
"outputs": [],
55+
"source": [
56+
"list_ = [2, 4, 6, 8, 10]"
57+
]
58+
},
59+
{
60+
"cell_type": "code",
61+
"execution_count": 3,
62+
"metadata": {},
63+
"outputs": [],
64+
"source": [
65+
"def binary_search(sorted_list, k):\n",
66+
" if len(sorted_list) < 2:\n",
67+
" \n",
68+
" if sorted_list[0] == k:\n",
69+
" return \"Found\"\n",
70+
" else:\n",
71+
" return \"Not Found\"\n",
72+
" else:\n",
73+
" mid = len(sorted_list) // 2\n",
74+
" if mid == k:\n",
75+
" return \"Found\"\n",
76+
" else:\n",
77+
" if k < sorted_list[mid]:\n",
78+
" return binary_search(sorted_list[:mid], k)\n",
79+
" else:\n",
80+
" return binary_search(sorted_list[mid:], k)"
81+
]
82+
},
83+
{
84+
"cell_type": "code",
85+
"execution_count": 5,
86+
"metadata": {},
87+
"outputs": [
88+
{
89+
"data": {
90+
"text/plain": [
91+
"'Not Found'"
92+
]
93+
},
94+
"execution_count": 5,
95+
"metadata": {},
96+
"output_type": "execute_result"
97+
}
98+
],
99+
"source": [
100+
"binary_search(list_, 16)"
101+
]
102+
},
103+
{
104+
"cell_type": "code",
105+
"execution_count": null,
106+
"metadata": {},
107+
"outputs": [],
108+
"source": []
109+
}
110+
],
111+
"metadata": {
112+
"kernelspec": {
113+
"display_name": "ml_env",
114+
"language": "python",
115+
"name": "python3"
116+
},
117+
"language_info": {
118+
"codemirror_mode": {
119+
"name": "ipython",
120+
"version": 3
121+
},
122+
"file_extension": ".py",
123+
"mimetype": "text/x-python",
124+
"name": "python",
125+
"nbconvert_exporter": "python",
126+
"pygments_lexer": "ipython3",
127+
"version": "3.9.18"
128+
}
129+
},
130+
"nbformat": 4,
131+
"nbformat_minor": 2
132+
}

0 commit comments

Comments
 (0)