Advanced python - Algorithm

  • Algorithm: the solution to the problem and steps

  • The quality evaluation algorithm: asymptotic asymptotic time complexity and space complexity.

  • Asymptotic time complexity of O large numerals:

    •  - constant time - Bloom filter / storage hash
    •  - logarithmic time complexity - binary search (binary search)
    •  - linear time - sequential search / sort barrel
    •  - log-linear time complexity - advanced sorting algorithms (merge sort, quick sort)
    •  - the square of the time complexity - a simple sorting algorithm (selection sort, insertion sort, bubble sort)
    •  - cubic time complexity - Floyd algorithm / matrix multiplication
    •  - geometrically time complexity - Tower of Hanoi
    •  - factorial time complexity - Travel dealers problems - NP

Sorting algorithms (selection, bubbling and merge) and search algorithm (sequential and binary)

Selection Sort (Selection sort) is a straightforward sorting algorithm. It works as follows. First, find the smallest sequence of unsorted (large) element, the starting position is stored in the sorted sequence, and then continue to find the minimum (large) element from the remaining elements of unsorted and sorted into the end of the sequence. And so on, until all the elements are sorted.

function:

def select_sort(origin_items, comp=lambda x, y: x < y): """简单选择排序""" items = origin_items[:] for i in range(len(items) - 1): min_index = i for j in range(i + 1, len(items)): if comp(items[j], items[min_index]): min_index = j items[i], items[min_index] = items[min_index], items[i] return items
选择排序例子:
def select_sort(items):

for i in range(len(items)):
min_index = i
for j in range(i+1,len(items)):
if items[min_index] > items[j]:
min_index = j
items[i],items[min_index] = items[min_index],items[i]

print('选择排序后的数组:')
for i in range(len(items)):
print('%d ' %items[i],end=' ')

def main():
items = [64, 25, 12, 22, 11]
select_sort(items)

if __name__ == '__main__':
main()
Bubble Sort (Bubble Sort) is also a simple and intuitive sorting algorithm. It repeatedly visited the number of columns to be sorted, a comparison of two elements, if they put them in the wrong order switching over. 
The number of visits to the column work is repeated until there is no longer need to swap, that is to say the number of columns already sorted completed. The origin of the name of the algorithm is because the smaller elements will slowly through the exchange of "float" to the top of the columns.
function:
def bubble_sort(origin_items, comp=lambda x, y: x > y): """高质量冒泡排序(搅拌排序)""" items = origin_items[:] for i in range(len(items) - 1): swapped = False for j in range(i, len(items) - 1 - i): if comp(items[j], items[j + 1]): items[j], items[j + 1] = items[j + 1], items[j] swapped = True if swapped: swapped = False for j in range(len(items) - 2 - i, i, -1): if comp(items[j - 1], items[j]): items[j], items[j - 1] = items[j - 1], items[j] swapped = True if not swapped: break return items
例子1:
def bubble_sort(items):
n = len(items)
for i in range(n):
for j in range(0,n-i-1):
if items[j] > items[j+1]:
items[j],items[j+1] = items[j+1],items[j]
print('冒泡排序后的数组:')
for i in range(len(items)):
print('%d' %items[i],end=' ')

def main():
items = [64,34,25,12,22,11,90]
bubble_sort(items)

if __name__ == '__main__':
main()
例子2:
def bubble_sort(origin_items, comp=lambda x, y: x > y):
"""高质量冒泡排序(搅拌排序)"""
items = origin_items[:]
for i in range(len(items) - 1):
swapped = False
for j in range(i, len(items) - 1 - i):
if comp(items[j], items[j + 1]):
items[j], items[j + 1] = items[j + 1], items[j]
swapped = True
if swapped:
swapped = False
for j in range(len(items) - 2 - i, i, -1):
if comp(items[j - 1], items[j]):
items[j], items[j - 1] = items[j - 1], items[j]
swapped = True
if not swapped:
break
return items
def main():
items = [64,34,25,12,22,11,90]
bubble_sort(items)
for i in range(len(items)):
print('%d' %items[i],end=' ')

if __name__ == '__main__':
main()

Merge sort (English: Merge sort, or mergesort), is to create a merge operation on an efficient sorting algorithm.

The algorithm is very typical application uses a divide and conquer (Divide and Conquer) a.

Minute root treatment:

  • Segmentation: recursively divided equally in half the current sequence.
  • Integration: sequences while maintaining the order of the elements obtained in the previous step integrated together (merge).
function:
def merge_sort(items, comp=lambda x, y: x <= y): """归并排序(分治法)""" if len(items) < 2: return items[:] mid = len(items) // 2 left = merge_sort(items[:mid], comp) right = merge_sort(items[mid:], comp) return merge(left, right, comp)
DEF Merge ( items1, items2, CoMP): "" "merge (merging the two ordered list into an ordered list) " "" items = [] index, index2 = 0, 0 the while index1, < len (items1 ) and index2 < len (items2): IF CoMP (items1 [index1,], items2 [index2]): items.append (items1 [index1,]) index1, + = . 1 the else: items.append (items2 [index2]) index2 + = items. 1 + = items1 [index1,:] items + = items2 [index2:] return items 
example:
DEF merge_sort (items, CoMP = the lambda X, Y: X <= Y): 
"" "merge sort (Method of Division)" ""
IF len (items) <2:
return items [:]
MID = len (items) 2 //
left = merge_sort (items [: MID], CoMP)
right = merge_sort (items [MID:], CoMP)
return merge (left, right, CoMP)


DEF merge (items1, items2, CoMP):
"" "merge (the two merged into a single ordered list of ordered list) "" "
items = []
index1,, index2 = 0, 0
the while index1, <len (items1) and index2 <len (items2):
IF CoMP (items1 [ index1,], items2 [index2]):
items.append (items1 [index1,])
index1,. 1 + =
the else:
items.append(items2[index2])
index2 += 1
items += items1[index1:]
items += items2[index2:]
return items

def main():
items = [64,34,25,12,22,11,90]
merge_sort(items)
for i in range(len(items)):
print('%d' %items[i],end=' ')

if __name__ == '__main__':
main()

例子2:
DEF Merge (ARR, L, m, R & lt): 
N1 = m - L +. 1
N2 = R & lt - m

# Create a temporary array
L = [0] * (N1)
R & lt = [0] * (N2)

# copy data to temporary array arrays L [] and R & lt []
for I in Range (0, N1):
L [I] = ARR [L + I]

for J in Range (0, N2):
R & lt [J] = ARR [m + + J. 1]

# to merge the temporary array ARR [l..r]
I = 0 # initialization of the first sub-array index
j = 0 # initialization of the second sub array index
k = l # subarray initial index merging

while I <N1 and J <N2:
IF L [I] <= R & lt [J]:
ARR [K] = L [I]
I + =. 1
the else:
ARR [K] = R & lt [J]
J + =. 1
K + = 1

# copies L [] retention element
the while I <N1:
ARR [K] = L [I]
I + =. 1
K + =. 1

# copies R & lt [] retention elements
the while J <N2:
ARR [K] = R & lt [J]
J + =. 1
K + =. 1


DEF mergesort (ARR, L, R & lt):
IF L <R & lt:
m = int ((L + (R & lt -. 1)) / 2)

mergesort (ARR, L, m)
mergesort (ARR, m +. 1, R & lt )
Merge (ARR, L, m, R & lt)


ARR = [12 is,. 11, 13 is,. 5,. 6,. 7]
n-= len (ARR)
Print ( "the given array")
for I in Range (n-):
Print ( "% D"% ARR [I])

mergesort (ARR, 0, n -. 1)
Print ( "\ n \ after the n sorted array")
for I in Range (n):
Print ( "% D"% ARR [i])

Find the order refers to a certain order to check each element in the array, up to a certain value until you find're looking for.
function:
def seq_search(items, key):
    """顺序查找""" for index, item in enumerate(items): if item == key: return index return -1
例子:
seq_search DEF (items, n-, Key): 
for I in Range (0, n-):
IF items [I] == Key:
return I
return -1

DEF main ():
items = [64,34,25,12, 22,11]
Key = 22 is
n-= len (items)
Result = seq_search (items, n-, Key)
IF == -1 Result:
Print ( 'elements from the array!')
the else:
Print ( "elements in the array index ", Result)

IF the __name__ == '__main__':
main ()

Binary search is a search algorithm to find a particular element in an ordered array. Search process from the middle of the array elements, if the intermediate element the element is just looking for, the search process ends;
if a particular element is greater than or less than the intermediate element in the array is greater or less than half that of the intermediate element lookup, and Like start start comparing the middle element.
If the array is empty at some stage, it represents not found. This search algorithm so that each comparison search reduced by half.
Function:
DEFbin_search (items,Key):
    """折半查找""" start, end = 0, len(items) - 1 while start <= end: mid = (start + end) // 2 if key > items[mid]: start = mid + 1 elif key < items[mid]: end = mid - 1 else: return mid return -1
例子:
 
 
# Returns the index of arr x, if there is no return -1 
DEF binarySearch (arr, L, R & lt, x):
# substantially Analyzing
IF R & lt> = L:
MID int = (L + (R & lt - L) / 2)
good element for the entire intermediate position #
IF ARR [mID] == X:
return mID
# elements less than the intermediate position of the element, the element simply comparing the left again
elif ARR [mID]> X:
return binarySearch (ARR, L, mID - . 1, X)
# element is greater than the intermediate position of the element, the comparison element again just right
the else:
return binarySearch (ARR,. 1 + mID, R & lt, X)
the else:
# absence
return -1

DEF main ():
# test array
= ARR [2,. 3,. 4, 10, 40]
X 10 =
# function call
result = binarySearch (arr, 0, len (arr) - 1, x)
Result = -1 IF:!
Print ( "index of the element in the array is D%"% Result)
the else:
Print ( "not in the array element")

IF the __name__ == '__main__':
main ()
 

 

Guess you like

Origin www.cnblogs.com/wen-hai/p/11100485.html