+ 5

please if you see my code help me in this i want to make linear search algorithm work faster by adding these condition

compare (x, y) if x ==y retern room number if x < y type amassege not in array considering array is sorted if x> y continue in searching for key and return room number else return -3 that means element not in array I wont using this code in my project so I wont help please https://code.sololearn.com/ca8253nb01D5/?ref=app

3rd Jun 2018, 8:41 AM
Asmaa Mogahed Khalifa Osman
Asmaa Mogahed Khalifa Osman - avatar
5 Answers
+ 6
If You give Us method "definition", please use at least types. I know it is pseudo code, but trust me - I had to read carefully 4 times Your question. "if x ==y retern room number" -> return position in collection/array? "if x < y" -> You are comparing length of collection with input value? Please elaborate it more just for clearness. "if x> y continue in searching for the key and return room number" -> I might don't get this part in contradiction to the previous one, but let's give it a shot :) "else return -3 that means element not in array" -> clear enough As You can see, linear search is, well... Linear. That means complexity COULD be at worst case scenario equal to n, in avr. case n/2 comparisons. I deduced, that You are trying to do Linear Search with a sentinel, ordered, right? Basically what You are missing, is putting Your desired element at the very end of the collection. The approach of comparing "if x < y type amassege not in array considering array is sorted" is actually good, cause You have already iterated above the desired element. If You expected that comment, here it is, or You expect a working Java code?
3rd Jun 2018, 9:10 AM
Jakub DubaƄski
Jakub DubaƄski - avatar
+ 6
Ii think we missunderstood something here. Ways of making it faster are in my previous post, if You didnt manage to implement it, i can help when im back at home with laptop. Just let us know in this topic. :) Cheers!
3rd Jun 2018, 5:34 PM
Jakub DubaƄski
Jakub DubaƄski - avatar
+ 4
I compared elements in array with element I looking for not room with value linear search says that if element in array return room number else return - 3 but l wont make it faster by adding above conditions
3rd Jun 2018, 9:21 AM
Asmaa Mogahed Khalifa Osman
Asmaa Mogahed Khalifa Osman - avatar
+ 2
ok Rational Agent when you back to your home tell me by sending massage her thank you
3rd Jun 2018, 6:59 PM
Asmaa Mogahed Khalifa Osman
Asmaa Mogahed Khalifa Osman - avatar
+ 1
Change k <arr . length to something like (k <arr . length )&&(x < arr [k]) I think that will give the behavior you are looking for not sure if it's actually faster or not if its what you were after
3rd Jun 2018, 4:36 PM
Rational Agent