|
1 |
| -#Linear search for an element 'ele' in array 'a' |
2 |
| -#author-@rats123 |
3 |
| - |
4 |
| -def linear(a,ele): |
5 |
| - for i in range(len(a)): #for loop iterates through every single element in array |
6 |
| - if ele==a[i]: #if match is found it returns the index |
7 |
| - return i |
8 |
| - |
9 |
| - |
10 |
| - |
11 |
| - return 'Not found' |
12 |
| - |
13 |
| - |
14 |
| - |
15 |
| -##example run |
16 |
| - |
17 |
| - |
18 |
| -print(linear([1,2,3,4,5,6,12,23],4)) |
| 1 | +""" |
| 2 | + Linear search |
| 3 | + Search Key in an Array |
| 4 | + Written by: author-@rats123 |
| 5 | + Updated by: @ammarmallik |
| 6 | +""" |
| 7 | + |
| 8 | + |
| 9 | +def linear_search(arr, search_key): |
| 10 | + """ Algorithm: |
| 11 | + 1. If array is empty, return -2 |
| 12 | + 2. Iterate array and compare each value with search_key |
| 13 | + 3. if search_key is found, return index |
| 14 | + 4. Otherwise return -1 |
| 15 | + """ |
| 16 | + if arr: |
| 17 | + for index, element in enumerate(arr): |
| 18 | + if element == search_key: |
| 19 | + return index |
| 20 | + |
| 21 | + return -1 |
| 22 | + |
| 23 | + return -2 |
| 24 | + |
| 25 | + |
| 26 | +def print_result(search_key, index): |
| 27 | + """Returns error based on given index""" |
| 28 | + errors = { |
| 29 | + -1: "{} doesn't exist in array".format(search_key), |
| 30 | + -2: "Array is Empty" |
| 31 | + } |
| 32 | + print(errors[index] if index in errors else "Index: {}".format(index)) |
| 33 | + |
| 34 | + |
| 35 | +if __name__ == "__main__": |
| 36 | + """ Test cases """ |
| 37 | + |
| 38 | + samples = [ |
| 39 | + {"arr": [1, 2, 3, 4, 5], "search_key": 5}, |
| 40 | + {"arr": [], "search_key": 5}, |
| 41 | + {"arr": [1, 2, 3, 4, 5], "search_key": 6} |
| 42 | + ] |
| 43 | + |
| 44 | + for item in samples: |
| 45 | + index = linear_search(item.get("arr"), item.get("search_key")) |
| 46 | + print_result(item.get("search_key"), index) |
0 commit comments