GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — algorithms/search/first_occurance.py at master · deba999/algorithms Expand file tree/ Copy pathfirst_occurance.pyMore file actions 46 lines (40 loc) · 1.36 KB / Copy pathfirst_occurance.pyFile metadata and controls46 lines (40 loc) · 1.36 KB 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 # # Find first occurance of a number in a sorted array (increasing order) # Approach- Binary Search # T(n)- O(log n) # def firstOccurance(array, query): lo, hi = 0, len(array) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 print("lo: ", lo, " hi: ", hi, " mid: ", mid) if (mid == 0 and array[mid] == query) or \ (array[mid] == query and array[mid - 1] < query): return mid elif array[mid] <= query: lo = mid + 1 else: hi = mid - 1 def main(): array = [1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 6] print(array) print("-----SEARCH-----") query = 3 print("found first: ", query, " in index:", firstOccurance(array, query)) print("-----SEARCH-----") query = 5 print("found first: ", query, " in index:", firstOccurance(array, query)) print("-----SEARCH-----") query = 7 print("found first: ", query, " in index:", firstOccurance(array, query)) print("-----SEARCH-----") query = 1 print("found first: ", query, " in index:", firstOccurance(array, query)) print("-----SEARCH-----") query = -1 print("found first: ", query, " in index:", firstOccurance(array, query)) print("-----SEARCH-----") query = 9 print("found first: ", query, " in index:", firstOccurance(array, query)) if __name__ == "__main__": main() |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |