数据结构与算法基础

二分查找

时间复杂度为O(logN)

递推公式:
f(N) = f(N/2) + O(1) = f(N/4) + 2 * O(1)
假设 N = 2 ^ M
最后可以推出
f(N) = O(logN)

// O(N)
def LinearSearch(array, t):
    for i in range(len(array)):
        if array[i] == t:
            return True
    return False

// O(logN)
def BinarySearch(array, t):
    left = 0
    right = len(array) - 1
    while left <= right:
        mid = int((left + right) / 2)
        if array[mid] < t:
            left = mid + 1
        elif array[mid] > t:
            right = mid - 1
        else:
            return True
    return False
    

递归实现
left是搜索的起始下标,right是搜索的结尾下标

def RecursiveBinarySearch(array, t, left, right):
    if left <=right:
        # 数组中间元素的下标
        mid = int((left + right) / 2)
        if array[mid] < t:
            RecursiveBinarySearch(array, t, mid+1, right)
        elif array[mid] > t:
            RecursiveBinarySearch(array, t, left, mid-1)
        else:
            return mid 
    return -1 
    
array = list(range(100000000))


import time

t1 = time.time()
LinearSearch(array, 100000001)
t2 = time.time()
print('线性查找:', t2 - t1)

t3 = time.time()
BinarySearch(array, 100000001)
t4 = time.time()
print('二分查找:', t4 - t3)

快速排序

# 时间复杂度__O(NlogN)
def partition(A, p, r):
    # x为分割操作的哨兵
    x = A[r]
    i = p - 1
    # 从p遍历到r-1,也就是说不遍历哨兵
    for j in range(p, r):
        if A[j] <= x:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i + 1], A[r] = A[r], A[i + 1]
    return i + 1


def quick_sort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quick_sort(A, p, q - 1)
        quick_sort(A, q + 1, r)


A = [2, 45, 6, 2, 7, 2, 7, 8, 4]
quick_sort(A, 0, 8)
print(A)

插入排序

# 时间复杂的__O(N^2)
def insert_sort(A):
	for i in range(1, len(A)):
		key = A[i]
		j = i - 1
		while A[j] > key and j >= 0:
			A[j + 1] = A[j]
			j -= 1
		A[j + 1] = key
	return A
A = [2, 45, 6, 2, 7, 2, 7, 8, 4]
print(insert_sort(A))

你可能感兴趣的:(二分查找)