Classic sorting and summary (python achieve)

1. Sort the basic concepts and classification

The so-called sequencing, is to make a bunch of records, which follow a certain size or certain keywords, increasing or decreasing line up operations. Sorting algorithm, it is how to make the recording method according to claim arrangement.

Sort of stability:

After some sort, if two record number equal, and both have the original order in the chaotic record remains the same, sorting method used is called stable, whereas unstable.

Sort Sort inner and outer

The sort: sorting process, all the records to be sorted in all the memory
external sorting: sorting process, using the external memory.
They are within the usual sort of discussion.

Sorting within three factors affect the performance of the algorithm:

  • Time Complexity: That time performance, high efficiency of sorting algorithms should have as few keywords and the number of comparisons record number of moves
  • Space complexity: The main algorithm is executed auxiliary space required, the better.
  • The complexity of the algorithm. Mainly it refers to the complexity of the code.

The main operation by the sorting process, the sorting can be put into:

  • Insertion Sort
  • Sort exchange
  • Selection Sort
  • Merge sort

According to the complexity of the algorithm can be divided into two categories:

  • Simple algorithm: comprising a bubble sort, simple and direct insertion sort selection sort
  • Improved algorithms include: Hill sort, heap sort, merge sort and quick sort

The following seven sorting algorithm sorting algorithm in all but the most classic of several, does not mean all of them.

2. bubble sort BubbleSort

Introduction:

Bubble sort is very simple principle, which repeatedly visited the number of columns to be sorted, a comparison of two elements, if they put them in the wrong order switching over.

step:

  1. Compare adjacent elements. If the first is greater than the second, the two of them exchanged.
  2. Do the same for the 0-th to the n-1 data. At this time, the largest number on the "float" to the last position on the array.
  3. Repeat these steps for all elements, except the last one.
  4. Continued to repeat the above steps for each time fewer and fewer elements, a pair of numbers until there is no need to compare.

python achieve

def bubble_sort(arr):
    n = len(arr)
    # 遍历所有数组元素
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:     #如果前者比后者大
                arr[j], arr[j + 1] = arr[j + 1], arr[j]      #则交换两者
    return print(arr)

arr = [64, 34, 25, 12, 22, 11, 90]

bubble_sort(arr)

3. Select the sort SelectionSort

Introduction:

Select sort is undoubtedly the most straightforward sort. It works as follows.

step:

  1. Find the minimum (large) is not an element in the sorted sequence, starting position is stored in the sorted sequence.
  2. From the remaining unsorted then continue to look for the minimum element (large) element, and then into the end of the sorted sequence.
  3. And so on, until all the elements are sorted.

python achieve

def select_sort(arr):
    n = len(arr)
    for i in range(n):
        min = i  # 最小元素下标标记
        for j in range(i + 1, n):
            if arr[j] < arr[min]:
                min = j  # 找到最小值的下标
        arr[min], arr[i] = arr[i], arr[min]  # 交换两者
    return print(arr)


arr = [64, 34, 25, 12, 22, 11, 90]
select_sort(arr)

4. insertion sort InsertionSort

Introduction:

Insertion sort works, for each unsorted data, scanning in the sorted sequence from back to front, and find the corresponding insertion positions.

step:

  1. From the beginning of the first element, the element can be considered to have been sorted
  2. Remove the next element from the scanner forward in the sequence of elements has been ordered
  3. If the scanned element (sorted) is greater than the new element, the element after a move
  4. Repeat step 3 until it finds the sorted elements less than or equal to the new position of the element
  5. After the new element is inserted into the position
  6. Repeat steps 2 to 5

Sort presentation:

img

python achieve

def inset_sort(arr):
    n = len(arr)
    for i in range(1,n):
        if arr[i] < arr[i-1]:
            temp = arr[i]
            index = i  # 待插入的下标
            for j in range(i-1,-1,-1):   # 从i-1 循环到 0 包括0
                if arr[j] > temp:
                    arr[j+1] = arr[j]
                    index = j   # 记录待插入的下标
                else:
                    break
            arr[index] = temp
    return print(arr)


arr = [64, 34, 25, 12, 22, 11, 90]
inset_sort(arr)

5. Hill sorting ShellSort

Introduction:

Hill sorting, also called descending increments sorting algorithm , in essence, is a packet insertion sort. Proposed by Donald Shell in 1959. Hill sorting non-stationary sorting algorithm.

Hill is the basic idea of ​​the sort: the array of columns and column insertion sort are in a table, repeat this process, but each time with a longer column (step longer, less the number of columns) to . 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, suppose there is such a set of numbers [ 13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10 ], if we start with a step size of 5 to sort, we have a list of these can be placed on the table by five of the algorithm to better describe, so they should look like this:

13 14 94 33 82
25 59 94 65 23
45 27 73 25 39
10

Then we sort each column:

10 14 73 25 23
13 27 94 33 39
25 59 94 65 82
45

When the above four lines of numbers, we get together in sequence: [ 10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45 ]. Case 10 has been moved to the correct position, and then to step 3 to sort:

10 14 73
25 23 13
27 94 33
39 25 59
94 65 82
45

After sorting becomes:

10 14 13
25 23 33
27 25 59
39 65 73
45 94 82
94

Finally sort 1 step (at this time is a simple insertion sort).

python achieve

def shell_sort(ary):
    n = len(ary)
    gap = round(n/2)       #初始步长 , 用round四舍五入取整
    while gap > 0 :
        for i in range(gap,n):        #每一列进行插入排序 , 从gap 到 n-1
            temp = ary[i]
            j = i
            while ( j >= gap and ary[j-gap] > temp ):    #插入排序
                ary[j] = ary[j-gap]
                j = j - gap
            ary[j] = temp
        gap = round(gap/2)                     #重新设置步长
    return print(ary)
ary = [13, 14, 94, 33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10]
shell_sort(ary)

6. merge sort MergeSort

Introduction:

Merge sort is a very typical application using divide and conquer method. 归并Sort of thinking is the first delivery of decomposition array, again and arrays.

First consider merging two ordered arrays, the basic idea is to compare two arrays front of the number, and who will take the first small who, after taking the corresponding pointer moved back one. Then comparison, an array of empty until the last remaining portion of the copied over to the other array.

Consider recursive decomposition, the basic idea is to break down into an array leftand right, if both the internal data arrays are ordered, then you can use the above method merge the two arrays of arrays merge sort. How to make these two internal arrays are ordered? It can be re-half, until decomposition time until the group contains only one element, that the interior of the case group had ordered. Then the two groups to merge sort neighbor.

Sort presentation:

img

python achieve

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


def merge(left, right):
    '''合并操作,
    将两个有序数组left[]和right[]合并成一个大的有序数组
    '''
    l, r = 0, 0  # left与right数组的下标指针
    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


ary = [13, 14, 94, 33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10]
merge_sort(ary)

7. Quick Sort QuickSort

Description:
Quick sort is usually significantly higher than the same Ο (n log n) other algorithms faster, so frequently used, and fast row using a divide and conquer idea, so in many written interview can often see fast row shadow. Quick to grasp the importance of visible rows.

step:

  1. Pick from a number of elements as the reference number of the column.
  2. Partitioning process, than the reference number into the right side of the large, less than or equal to its number are placed on the left.
  3. Then the second step to the left and right sections recursively until each section is only a number.

Sort presentation:

img

python achieve

def quick_sort(ary):
    return qsort(ary, 0, len(ary) - 1)


def qsort(ary, left, right):
    # 快排函数,ary为待排序数组,left为待排序的左边界,right为右边界
    if left >= right: return ary
    key = ary[left]  # 取最左边的为基准数
    lp = left  # 左指针
    rp = right  # 右指针
    while lp < rp:
        while ary[rp] >= key and lp < rp:
            rp -= 1
        while ary[lp] <= key and lp < rp:
            lp += 1
        ary[lp], ary[rp] = ary[rp], ary[lp]
    ary[left], ary[lp] = ary[lp], ary[left]
    qsort(ary, left, lp - 1)
    qsort(ary, rp + 1, right)
    return ary


ary = [13, 14, 94, 33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10]
quick_sort(ary)

8. heap sort HeapSort

Introduction:

Heapsort use more frequently in the top K in question. Heap sort is the use of a binary heap data structure to achieve, though still substantially one-dimensional array. Binary heap is approximately a complete binary tree.

Binary heap has the following properties:

  1. Key of the parent node is always greater than or equal to (less than or equal to) a key to any child nodes.
  2. Right and left sub-tree of each node is a binary heap (heap is the maximum or minimum heap).

step:

  1. The maximum stack configuration (Build_Max_Heap): If the array subscript range of 0 ~ n, taking into account the large root element is a single stack, from the index n/2element start are large root stack. So long from the n/2-1start, followed by a forward structure large root heap, so that we can ensure that, when built into a node, its left and right subtrees are already large root heap.
  2. Heap sort (HeapSort): Since the pile array is simulated. After obtaining a large root heap, the internal array is not orderly. So we need to stack an array of ordering. The idea is to remove the root node, and make adjustments largest heap of recursive operations. The first time heap[0]with the heap[n-1]exchange, and then to heap[0...n-2]do the maximum heap adjustment. The second will be heap[0]the heap[n-2]exchange, and then to heap[0...n-3]do the maximum heap adjustment. This operation is repeated until heap[0]and heap[1]exchange. Because every time the maximum number of ordered incorporated into the back section, so that after operation of the entire array is ordered.
  3. Maximum adjustment stack (Max_Heapify): This method is to provide the above-described two procedure calls. The aim is to end the child node heap adjusted, so that the child node is always less than the parent node.

Sort presentation:

img

python achieve

def heap_sort(ary):
    n = len(ary)
    first = int(n / 2 - 1)  # 最后一个非叶子节点
    for start in range(first, -1, -1):  # 构造大根堆
        max_heapify(ary, start, n - 1)
    for end in range(n - 1, 0, -1):  # 堆排,将大根堆转换成有序数组
        ary[end], ary[0] = ary[0], ary[end]
        max_heapify(ary, 0, end - 1)
    return print(ary)


# 最大堆调整:将堆的末端子节点作调整,使得子节点永远小于父节点
# start为当前需要调整最大堆的位置,end为调整边界
def max_heapify(ary, start, end):
    root = start
    while True:
        child = root * 2 + 1  # 调整节点的子节点
        if child > end: break
        if child + 1 <= end and ary[child] < ary[child + 1]:
            child = child + 1  # 取较大的子节点
        if ary[root] < ary[child]:  # 较大的子节点成为父节点
            ary[root], ary[child] = ary[child], ary[root]  # 交换
            root = child
        else:
            break


ary = [13, 14, 94, 33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10]
heap_sort(ary)

Seven kinds of sorting algorithm performance comparison

Here are seven classical sorting algorithm comparison of indicators:

img

  • If the column to be sorted basic order, please use a simple algorithm, do not use complex algorithms to improve.
  • Merge sort and quick sort, although high performance, but requires more auxiliary space. In fact, it is to use space for time.
  • The fewer number of elements to be sorted column, suitable for the more simple method of sorting; the greater the number of elements more suitable for an improved sorting algorithm.
  • Simple selection sort, although not on time performance, but it is in space utilization is high on performance. Particularly suitable, those little amount of data, sorting data and information each more of a class of elements.

General content of the reference blog: https://www.cnblogs.com/zhizhan/p/4549099.html

Guess you like

Origin www.cnblogs.com/nangec/p/12019946.html