-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchAlgo.py
375 lines (312 loc) · 12.2 KB
/
SearchAlgo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
from flask import Flask,redirect,url_for,render_template,request,jsonify
import random
import datetime
import copy
import time
import json
#Empty array initialized to use across different functions
uniqueArr ,uniqueSorted = [],[]
root=None
RBT=None
app = Flask(__name__)
@app.route('/',methods = ['GET','POST'])
def index():
return render_template('SearchAlgo.html')
@app.route('/generateAllDS',methods = ['GET','POST'])
def generateAllDS():
global uniqueArr
global uniqueSorted
global root
global RBT
inputsize = 0
userarray = 0
try:
userarray=request.json['userarray']
except KeyError:
print('No userarray')
test = request.json.get(inputsize, 0)
try:
inputsize = int(request.json['inputsize'])
except KeyError:
print('No inputsize')
if inputsize != 0:
uniqueArr = random.sample(range(inputsize*1000), inputsize)
else:
uniqueArr=[int(e) for e in userarray.split(',')]
#Sorted array for binary search
uniqueSorted = sorted(uniqueArr)
#Insert values in Binary search tree and create its DS
root=insert(None,uniqueArr[0])
for i in range(1,len(uniqueArr)):
insert(root,uniqueArr[i])
preorderTraversalBST(root)
#Insert values in Red black tree and create its DS
RBT = RBTree()
rbtroot = None
for i in range(len(uniqueArr)):
rbtroot = RBT.insertRBTNode(uniqueArr[i])
dataStructureArray = dict()
#RBT.preorderTraversalRBT()
#6 12 100000//12
#7 14
if inputsize != 0 and inputsize>10000:
l = len(uniqueArr)//2
dataStructureArray['unique']=uniqueArr[:2500]+uniqueArr[l-1250:l+1250]+uniqueArr[-2500:]
else:
dataStructureArray['unique']=uniqueArr
return dataStructureArray
@app.route('/generateBSTDS',methods = ['GET','POST'])
def generateBSTDS():
global root
dictPreOrderBST=dict()
dictPreOrderBST['BST']=preorderTraversalBST(root)
return dictPreOrderBST
@app.route('/generateRBTDS',methods = ['GET','POST'])
def generateRBTDS():
global RBT
dictPreOrderRBT=dict()
res = RBT.preorderTraversalRBT()
dictPreOrderRBT['RBT']= res
return dictPreOrderRBT
@app.route('/generateBSDS',methods = ['GET','POST'])
def generateBSDS():
global uniqueSorted
dictBS=dict()
dictBS['BS']= uniqueSorted
return dictBS
@app.route('/searchAllElements',methods = ['GET','POST'])
def searchAllElements():
global uniqueArr,uniqueSorted,root,RBT
searchElement = int(request.json['searchelement'])
selectedAlgo = request.json['selectedAlgo']
arr_time_LS = []
arr_time_BS = []
arr_time_BST = []
arr_time_RBT= []
dataRunningTime = dict()
for j in selectedAlgo:
if j == "LS":
for i in range(10):
a1 = datetime.datetime.now()
f = linear_search(uniqueArr, searchElement)
b1 = datetime.datetime.now()
c1 = b1 - a1
arr_time_LS.append(c1.microseconds)
dataRunningTime[j] = [avg(arr_time_LS),f]
if j == "BS":
for i in range(10):
a1 = datetime.datetime.now()
f = binary_search(uniqueSorted, searchElement)
b1 = datetime.datetime.now()
c1 = b1 - a1
arr_time_BS.append(c1.microseconds)
dataRunningTime[j] = [avg(arr_time_BS),f]
if j == "BST":
for i in range(10):
a1 = datetime.datetime.now()
f = bstSearch(root, searchElement)
b1 = datetime.datetime.now()
c1 = b1 - a1
arr_time_BST.append(c1.microseconds)
dataRunningTime[j] = [avg(arr_time_BST),f]
if j == "RBT":
for i in range(10):
a1 = datetime.datetime.now()
f = RBT.search(searchElement)
b1 = datetime.datetime.now()
c1 = b1 - a1
arr_time_RBT.append(c1.microseconds)
dataRunningTime[j] = [avg(arr_time_RBT),f]
return dataRunningTime
#------------------------------------Binary search-----------------------------------------------------------------------------------------------------------------
def binary_search(inputarray, searchvalue):
start = 0
end = len(inputarray) - 1
mid = 0
while start <= end:
mid = (end + start) // 2
if inputarray[mid] == searchvalue:
return True
if inputarray[mid] < searchvalue:
start = mid + 1
elif inputarray[mid] > searchvalue:
end = mid - 1
return False
#------------------------------------linear search---------------------------------------------------------------------------------------------------------
def linear_search(inputarray, searchvalue):
for i in range(0,len(inputarray)):
if inputarray[i] == searchvalue:
return True
return False
#----------------------------------------Binary Search Tree-----------------------------------------------------------------------------------------------------------------
#class defined for BST
class nodeBST:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
#Insertion function in BST
def insert(NodeBST, data):
if NodeBST == None:
return nodeBST(data)
if data < NodeBST.data:
NodeBST.left = insert(NodeBST.left, data)
elif data > NodeBST.data:
NodeBST.right = insert(NodeBST.right, data)
return NodeBST
#Function to search in RBT
def bstSearch(rootBST, key):
while rootBST != None:
if key == rootBST.data:
return True
if key > rootBST.data:
rootBST = rootBST.right
elif key < rootBST.data:
rootBST = rootBST.left
return False
#Preorder Traversal BST
def preorderTraversalBST(rootBST):
result = []
if rootBST:
result.append(rootBST.data)
result = result + preorderTraversalBST(rootBST.left)
result = result + preorderTraversalBST(rootBST.right)
# print(result,"BST")
return(result)
#----------------------------------------------------------------RBT --------------------------------------------------------------------------------------------------------------------------------
class RBTNode():
def __init__(self,data):
self.data = data
self.parent = None
self.left = None
self.right = None
self.color = "RED"
class RBTree():
def __init__(self):
self.element = RBTNode(0)
self.element.color = "BLACK"
self.element.left = None
self.element.right = None
self.root = self.element
# Insert New RBTNode
def insertRBTNode(self, key):
node = RBTNode(key)
node.parent = None
node.data = key
node.left = self.element
node.right = self.element
node.color = "RED"
tempNode = None
newNode = self.root
while newNode != self.element:
tempNode = newNode
if node.data < newNode.data:
newNode = newNode.left
else:
newNode = newNode.right
node.parent = tempNode
if tempNode == None :
self.root = node
elif node.data < tempNode.data :
tempNode.left = node
else :
tempNode.right = node
if node.parent == None :
node.color = "BLACK"
return
if node.parent.parent == None :
return
self.fixPosition (node)
# Left rotation RBT
def rotateLeft (self , newNode ) :
tempNode = newNode.right
newNode.right = tempNode.left
if tempNode.left != self.element :
tempNode.left.parent = newNode
tempNode.parent = newNode.parent
if newNode.parent == None :
self.root = tempNode
elif newNode == newNode.parent.left :
newNode.parent.left = tempNode
else :
newNode.parent.right = tempNode
tempNode.left = newNode
newNode.parent = tempNode
#Right rotation RBT
def rotateRight ( self , newNode ) :
tempNode = newNode.left
newNode.left = tempNode.right
if tempNode.right != self.element :
tempNode.right.parent = newNode
tempNode.parent = newNode.parent
if newNode.parent == None :
self.root = tempNode
elif newNode == newNode.parent.right :
newNode.parent.right = tempNode
else :
newNode.parent.left = tempNode
tempNode.right = newNode
newNode.parent = tempNode
# Fix Up Insertion
def fixPosition(self, fixNode):
while fixNode.parent.color == "RED":
if fixNode.parent == fixNode.parent.parent.right:
u = fixNode.parent.parent.left
if u.color == "RED":
u.color = "BLACK"
fixNode.parent.color = "BLACK"
fixNode.parent.parent.color = "RED"
fixNode = fixNode.parent.parent
else:
if fixNode == fixNode.parent.left:
fixNode = fixNode.parent
self.rotateRight(fixNode)
fixNode.parent.color = "BLACK"
fixNode.parent.parent.color = "RED"
self.rotateLeft(fixNode.parent.parent)
else:
u = fixNode.parent.parent.right
if u.color == "RED":
u.color = "BLACK"
fixNode.parent.color = "BLACK"
fixNode.parent.parent.color = "RED"
fixNode = fixNode.parent.parent
else:
if fixNode == fixNode.parent.right:
fixNode = fixNode.parent
self.rotateLeft(fixNode)
fixNode.parent.color = "BLACK"
fixNode.parent.parent.color = "RED"
self.rotateRight(fixNode.parent.parent)
if fixNode == self.root:
break
self.root.color = "BLACK"
# # Function for preorder traversal of RBT
def preorderRBT (self,node) :
res=[]
if node != self.element:
res.append(node.data)
res = res + self.preorderRBT(node.left)
res = res + self.preorderRBT(node.right)
#print(res,"Red black tree")
return res
def preorderTraversalRBT(self) :
return self.preorderRBT(self.root)
#Function for search in RBT
def search(self,key):
return self.search_helper(self.root, key)
def search_helper(self,node,key):
while node != self.element:
if key == node.data:
return True
if key < node.data:
node = node.left
else:
node = node.right
return False
def avg(arr):
return timeFunc(round(sum(arr[1:])/len(arr[1:]),2))
def timeFunc(t):
return t
if __name__ == '__main__':
app.run(host='localhost',port=9874,debug=True)