python algorithm diagram - quickly sort and select Sort

Copyright: Shallow @ Copyright original article may not be reproduced without permission https://blog.csdn.net/xili2532/article/details/91372648

Divide and rule

A well-known recursive problem solving:Divide and rule. (Divide and conquer, D & C ).
Works D & C's:
(1) identify simple baseline condition;
(2) determine how to reduce the scale of the problem so that it meets baseline conditions
required baseline conditions:Relates to the preparation of a recursive function array, the array baseline conditions usually is empty or contains only one element. When in trouble, check the baseline condition is not the case.
Example 1: write a recursive function to calculate the number of elements contained in the list and

def sum(list):
    if list == []:
        return 0
    else:
        return list[0] + sum(list[1:])

Two combined list can be added directly

Quick Sort

In a quick sort of ideological divide and rule,
step quick sort of:
(1) select the reference value.
(2) the array into two sub-arrays: an element is smaller than the reference value and the reference value is greater than the element.
(3) These two sub-arrays quickly sorted.
Examples of quick sort (the idea of using recursive):
simple algorithm Description: Select the first element of the array bit reference value, create two new arrays were stored elements than the reference value and greater than the reference value. Then two new arrays recursively above-described operation until the array is empty. The reference value is then left array and splicing

def quicksort(array):
  if len(array) < 2:
    # 基线条件:为空或只包含一个元素的数组是“有序”的
    return array
  else:
    pivot = array[0]
    # 由所有小于基准值的元素组成的子数组
    less = [i for i in array[1:] if i <= pivot]
    # 由所有大于基准值的元素组成的子数组
    greater = [i for i in array[1:] if i > pivot]

    return quicksort(less) + [pivot] + quicksort(greater)

Selection Sort

Selection sort steps of: traversing, to find a minimum value, and then added to a new list, cycle
each selection smallest element in the corresponding position

@pysnooper.snoop()
def findSmallest(arr):
    smallest = arr[0]
    smallest_index = 0
    for i in range(1, len(arr)):
        if arr[i] < smallest:
            smallest = arr[i]
            smallest_index = i
    return smallest_index


@pysnooper.snoop()
def selectionSort(arr):
    newArr = []
    for i in range(len(arr)):
        smallest = findSmallest(arr)
        newArr.append(arr.pop(smallest))
    return newArr

print(selectionSort([5, 3, 6, 2, 10]))

Bubble Sort

Comparing adjacent elements, each element of the selected maximum, for a comparison, the largest element can thus be the same as bubbling, from one location to reach the top.
Operation of bubble sort algorithm is as follows:
① compare adjacent elements. If the first than the second large (in ascending order), the two of them exchanged. Do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair. Once this is done, the last element is the biggest number.
② Repeat the above steps for all elements, except the last one. Continued to repeat the above steps for each time fewer and fewer elements, a pair of numbers until there is no need to compare.

@pysnooper.snoop()
def bubble_sort(alist):
    for j in range(len(alist) - 1, 0, -1):
        # j表示每次遍历需要比较的次数,是逐渐减小的
        for i in range(j):
            if alist[i] > alist[i + 1]:
                # 大的话交换位置
                alist[i], alist[i + 1] = alist[i + 1], alist[i]

li = [54, 26, 93, 17, 77, 31, 44, 55, 20]
bubble_sort(li)
print(li)

Insertion Sort

The array is divided into two front and rear portions, the front portion of the set of elements is sorted, the collection of elements is a part of unsorted. Select the first array each unsorted, sorted inserted into the appropriate location in the collection.
Working principle : Construction of an ordered sequence by, for unsorted data, scan in sorted sequence from back to front, i.e. by comparing the position and find the corresponding insert. Insertion sort in the realization, from back to front in the scanning process, the need to repeatedly ordered elements gradually move back position, to provide space for the insertion of new elements.And similar bubble sort

Here Insert Picture Description

def insert_sort(alist):
    # 从第二个位置,即下标为1的元素开始向前插入
    for i in range(1, len(alist)):
        # 从第i个元素开始向前比较,如果小于前一个元素,交换位置
        for j in range(i, 0, -1):
            if alist[j] < alist[j - 1]:
                alist[j], alist[j - 1] = alist[j - 1], alist[j]
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
insert_sort(alist)
print(alist)

Shell sort

Shell sort is optimized insertion sort, insertion sort, each element of each of the current and previous comparison elements, and then inserted, Shell sort, according to a certain length corresponding to the first step, the array groups, each group insertion sort, so that you can adjust the distribution of significant data, and finally performs a quick sort to fine-tune
the basic idea : the array of columns in a table and insertion sort columns, respectively, repeat this process, but each time with more column length (longer step size, the fewer the number of columns) is performed. Finally, the entire table is only one of. Convert the array to the table in order to better understand this algorithm, the algorithm itself or use an array to be sorted.

For example, assume there is such a set of numbers [1,314,943,382,255,994 6,523,452,773,253,910], if we start step is 5 sorts, we have placed these lists by 5 the table to better describe the algorithm, so they should look like this (vertically element is composed of steps):

def shell_sort(alist):
    n = len(alist)
    # 初始步长
    gap = int(n / 2)
    while gap > 0:
        # 按步长进行插入排序
        for i in range(gap, n):
            j = i
            # 插入排序
            while j >= gap and alist[j - gap] > alist[j]:
                alist[j - gap], alist[j] = alist[j], alist[j - gap]
                j -= gap
        # 得到新的步长
        gap = int(gap / 2)
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
shell_sort(alist)
print(alist)

Merge sort

Top-down: the first array by recursively decomposing, then merge array
algorithm is a brief description:
  Decomposition array: if an array of length 1, the intermediate from the array into two parts, the decomposition continues
  to create a fusion decomposed array,: merge array the new array, the array elements will be integrated for storage. To create a pointer pointing to the first two arrays, comparing the current position of the pointer to the size of the element, the new element into a smaller array, the pointer is moved backward, until a whole array element removed. The last two array inspection, the element is not removed appended to the new array, and finally stored into the array to be sorted according to the corresponding position in the sorted array.
  
Here Insert Picture Description

def merge_sort(alist):
    if len(alist) <= 1:
        return alist
    # 二分分解
    num = int(len(alist) / 2)
    left = merge_sort(alist[:num])
    right = merge_sort(alist[num:])
    # 合并
    return merge(left, right)

def merge(left, right):
    '''合并操作,将两个有序数组left[]和right[]合并成一个大的有序数组'''
    # left与right的下标指针
    l, r = 0, 0
    result = []
    while l < len(left) and r < len(right):
        if left[l] < right[r]:
            result.append(left[l])
            l += 1
        else:
            result.append(right[r])
            r += 1
    result += left[l:]
    result += right[r:]
    return result
alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
sorted_alist = merge_sort(alist)
print(sorted_alist)

Link: Several sorting algorithms .

Guess you like

Origin blog.csdn.net/xili2532/article/details/91372648