From 594ce80491f302ca35a28d6ba997c39b2ff52531 Mon Sep 17 00:00:00 2001 From: Abhishek2019 Date: Tue, 29 Oct 2019 22:35:28 +0800 Subject: [PATCH] sort and search algo added --- Searching Algorithm/binary_search.py | 29 ++++++++++++++++++++++++++++ Sorting Algorithm/bfs.py | 27 ++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 Searching Algorithm/binary_search.py create mode 100644 Sorting Algorithm/bfs.py diff --git a/Searching Algorithm/binary_search.py b/Searching Algorithm/binary_search.py new file mode 100644 index 0000000..644f98f --- /dev/null +++ b/Searching Algorithm/binary_search.py @@ -0,0 +1,29 @@ +# +# Binary search works for a sorted array. +# Note: The code logic is written for an array sorted in +# increasing order. +# T(n): O(log n) +# +def binary_search(array, query): + lo, hi = 0, len(array) - 1 + while lo <= hi: + mid = (hi + lo) // 2 + val = array[mid] + if val == query: + return mid + elif val < query: + lo = mid + 1 + else: + hi = mid - 1 + return None + +def binary_search_recur(array, low, high, val): + if low > high: # error case + return -1 + mid = (low + high) // 2 + if val < array[mid]: + return binary_search_recur(array, low, mid - 1, val) + elif val > array[mid]: + return binary_search_recur(array, mid + 1, high, val) + else: + return mid diff --git a/Sorting Algorithm/bfs.py b/Sorting Algorithm/bfs.py new file mode 100644 index 0000000..5fca2f4 --- /dev/null +++ b/Sorting Algorithm/bfs.py @@ -0,0 +1,27 @@ +def bfs(graph, start): + """ + return the set of all nodes that can be visited in the graph from start node + """ + visited = set() + queue = [start] + while queue: + current = queue.pop(0) + if current not in visited: + visited.add(current) + queue.extend(graph[current] - visited) + return visited + +def bfs_path(graph, start, end): + """ + return if there is a possible path from start node to end node in the graph + """ + visited = set() + queue = [start] + while queue: + current = queue.pop(0) + if current not in visited: + if current == end: + return True + visited.add(current) + queue.extend(graph[current] - visited) + return False