Algorithm basics _ binary search

I have nothing to do, I am interested in python, I bought this algorithm diagram, I hope it is like reading a novel, hehe

Goals:
(1) Master binary search
(2) Master data structure (array, linked list)
(3) Master recursion
(4) Master problem solving skills
(5) Master data structure (hash table)
(6) Master graph algorithm
(7) Master the K nearest neighbor algorithm
(8) understand some other algorithms

What is an algorithm?
It is a set of instructions to complete a task, and any code fragment can be regarded as an algorithm.

Why look at the algorithm?
Use common algorithm techniques to improve code execution speed.

What is binary search?
In the ordered list of elements , quickly find the element you want. It only takes x times, and the x power of 2 = N (n is the number of input elements).
For example: in 4 billion ordered elements, it only takes 36 times to find the content you input. This is really awesome

def binary_search(list, item):
    low = 0
    high = len(list)-1

    while low <= high:
        mid = int((low + high)/2)
        guess = list[mid]
        if guess == item:
            return mid
        if guess >item:
            high = mid - 1
        else:
            low = mid + 1
    return None


if __name__ == "__main__":
    my_list = [1, 3, 5, 6, 7, 8, 9]

    # 代表的是列表中的第几个元素
    a = binary_search(my_list, 9)
    # 输出是None,则说明没有这个元素
    b = binary_search(my_list, -1)
    print(a)
    print(b)
		
	

The running time of the algorithm is not measured in seconds. It is measured in terms of its growth rate. The running time is expressed in Big O notation. Binary search is much faster than simple search.
Big 0 notation: the running time of the algorithm.
O(log n): Logarithmic time, including binary search.
O(n): linear time, including simple search
O(n * log n): fast sorting, a faster sorting algorithm
O(n squared): selective sorting, slower sorting algorithm
O(n! ): Very slow algorithm, n different cities, how to ensure the shortest journey? To be sure, you have to list all permutations and combinations, and the number of permutations and combinations is the factorial of n.

Guess you like

Origin blog.csdn.net/weixin_45451320/article/details/114108530