📅  最后修改于: 2023-12-03 15:42:15.495000             🧑  作者: Mango
本章是GATE-CS-2003的试卷中的第65章,主要涉及以下内容:
本章讨论了几种常见的排序算法,包括冒泡排序、快速排序和归并排序。以下是一个示例的快速排序实现:
def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
def quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi-1)
quicksort(arr, pi+1, high)
本章讨论了几种图算法,包括深度优先搜索和广度优先搜索。以下是一个示例的深度优先搜索实现:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def DFS_util(self, v, visited):
visited.add(v)
print(v, end=' ')
for neighbor in self.graph[v]:
if neighbor not in visited:
self.DFS_util(neighbor, visited)
def DFS(self, v):
visited = set()
self.DFS_util(v, visited)
本章讨论了几种字符串算法,包括KMP算法和Boyer-Moore算法。以下是一个示例的KMP算法实现:
def compute_lps_array(pat, M, lps):
len = 0
lps[0] = 0
i = 1
while i < M:
if pat[i] == pat[len]:
len += 1
lps[i] = len
i += 1
else:
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1
def KMPSearch(pat, txt):
M = len(pat)
N = len(txt)
lps = [0]*M
j = 0
compute_lps_array(pat, M, lps)
i = 0
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
if j == M:
print("Found pattern at index " + str(i-j))
j = lps[j-1]
elif i < N and pat[j] != txt[i]:
if j != 0:
j = lps[j-1]
else:
i += 1
以上是本章的部分内容,更多的内容请参考GATE-CS-2003。