数据结构和算法是程序员的内功心法和基本功。无论是人工智能还是其它计算机科学领域,掌握扎实的数据结构和算法知识,往往会助力不少!今天给大家推荐一份不错的数据结构与算法资源。特点是:全代码实现!
这份资源的作者王争老师是前 Google 工程师,5 万+人跟着学的《数据结构和算法之美》专栏作者。他总结了程序员必备的 50 个数据结构与算法,以及相应的代码实现。开源地址为:
https://github.com/wangzheng0822/algo
我们来看一下这必备的 50 个数据结构与算法究竟包含了哪些内容。
数组
链表
栈
队列
递归
排序
二分查找
散列表
字符串
二叉树
堆
图
回溯
分治
动态规划
以上所有的数据结构与算法都配备相应的程序代码。一大特点是代码配备多种编程语言,例如 Python、C、Java、Go、Scala 等。

举例来说,关于常见的排序算法,例如冒泡排序、插入排序、选择排序,作者给出了相应的 Python 代码实现:
"""
Bubble sort, insertion sort and selection sort
冒泡排序、插入排序、选择排序
Author: Wenru
"""
from typing import List
# 冒泡排序
def bubble_sort(a: List[int]):
length = len(a)
if length <= 1:
return
for i in range(length):
made_swap = False
for j in range(length - i - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
made_swap = True
if not made_swap:
break
# 插入排序
def insertion_sort(a: List[int]):
length = len(a)
if length <= 1:
return
for i in range(1, length):
value = a[i]
j = i - 1
while j >= 0 and a[j] > value:
a[j + 1] = a[j]
j -= 1
a[j + 1] = value
# 选择排序
def selection_sort(a: List[int]):
length = len(a)
if length <= 1:
return
for i in range(length):
min_index = i
min_val = a[i]
for j in range(i, length):
if a[j] < min_val:
min_val = a[j]
min_index = j
a[i], a[min_index] = a[min_index], a[i]
def test_bubble_sort():
test_array = [1, 1, 1, 1]
bubble_sort(test_array)
assert test_array == [1, 1, 1, 1]
test_array = [4, 1, 2, 3]
bubble_sort(test_array)
assert test_array == [1, 2, 3, 4]
test_array = [4, 3, 2, 1]
bubble_sort(test_array)
assert test_array == [1, 2, 3, 4]
def test_insertion_sort():
test_array = [1, 1, 1, 1]
insertion_sort(test_array)
assert test_array == [1, 1, 1, 1]
test_array = [4, 1, 2, 3]
insertion_sort(test_array)
assert test_array == [1, 2, 3, 4]
test_array = [4, 3, 2, 1]
insertion_sort(test_array)
assert test_array == [1, 2, 3, 4]
def test_selection_sort():
test_array = [1, 1, 1, 1]
selection_sort(test_array)
assert test_array == [1, 1, 1, 1]
test_array = [4, 1, 2, 3]
selection_sort(test_array)
assert test_array == [1, 2, 3, 4]
test_array = [4, 3, 2, 1]
selection_sort(test_array)
assert test_array == [1, 2, 3, 4]
if __name__ == "__main__":
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
bubble_sort(array)
print(array)
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
insertion_sort(array)
print(array)
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
selection_sort(array)
print(array)当然,还有其它编程语言的代码实现,这里就不一一列举了!
目前,这份资源已经在 GitHub 上收获了 6000 星了。是一份不错的数据结构与算法参考代码。值得一看。最后再附上地址:
https://github.com/wangzheng0822/algo