Sort and search

Sort and search

Sorting algorithm: an algorithm that can arrange a string of data in a specific order

1. The stability of the sorting algorithm

stability: The stable sorting algorithm keeps the records with the same key value in the relative order, that is, if a sorting algorithm is stable, when there are two records with the same key value, R and S, and R appears in S in the original list Before, R will also be before S in the sorted list

(A stable algorithm may be more suitable for the needs of some practical situations. The order in the original sequence before sorting may imply some useful information, indicating some properties related to the actual problem, and a stable sorting algorithm will maintain these information and properties)

Adaptability: The sorting operation may be used to process sequences of different lengths. The description of complexity takes this problem into account. However, even the sorted sequence of the same length, the situation is very different, for example, sometimes the sorted sequence may be very different It is close to the sorted form, or it was originally a sorted sequence. In these cases, whether a sequence algorithm can complete the work faster, the adaptability of the sorting algorithm considers this issue.If a sorting algorithm works faster for close to ordered sequences, it is said to be adaptive, Adaptive algorithms also have practical value, because in practice it is often necessary to deal with sequences that are close to sorting

2. Classification of sorting algorithms

In order to understand the similarities and differences in ideas and practices of various sorting algorithms, people often divide classic sorting algorithms into some categories, common categories:

  • Insertion sort
  • Select sort
  • Exchange sort
  • Assignment order
  • Merge sort
  • External sort

3. Bubble sort

def bubble_sort(alist):
    n = len(alist)
    count = 0
    for j in range(n - 1):
        for i in range(0, n - 1 - j):
            if alist[i] > alist[i + 1]:
                alist[i], alist[i + 1] = alist[i + 1], alist[i]
                count += 1
        if count == 0:
            print(alist)
            return
    print(alist)


if __name__ == "__main__":
    bubble_sort([6, 5, 4, 3, 2, 1])
时间复杂度
 * 最优时间复杂度:O(n) 表示遍历一次没有发现任何可以交换的元素,排序结束
 * 最坏时间复杂度: O(n²)
 * 稳定性: 稳定

 暗号: 一个班长 比较两个 找到最大的放最后

Guess you like

Origin blog.csdn.net/weixin_46129834/article/details/113568694