Home >Backend Development >Python Tutorial >What are the python sorting algorithms?

What are the python sorting algorithms?

青灯夜游
青灯夜游forward
2020-04-21 16:47:553891browse

What are the sorting algorithms in python? The following article will introduce to you the top ten classic sorting algorithms in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

What are the python sorting algorithms?

Now many things can be solved with algorithms. In programming, algorithms play a very important role. Encapsulating algorithms with functions makes the program better. Call, no need to write repeatedly.

Python’s top ten classic algorithms:

1. Insertion sort

1. Algorithm idea

Start from the second element and compare it with the previous element. If the previous element is larger than the current element, then Move the previous element back, and the current element forward in turn, until an element smaller than or equal to it is found and inserted behind it,

Then select the third element, repeat the above operation, insert, and select in turn The last element, after insertion, completes all sorting.

2. Code implementation

def insertion_sort(arr):
    #插入排序
    # 第一层for表示循环插入的遍数
    for i in range(1, len(arr)):
        # 设置当前需要插入的元素
        current = arr[i]
        # 与当前元素比较的比较元素
        pre_index = i - 1
        while pre_index >= 0 and arr[pre_index] > current:
            # 当比较元素大于当前元素则把比较元素后移
            arr[pre_index + 1] = arr[pre_index]
            # 往前选择下一个比较元素
            pre_index -= 1
        # 当比较元素小于当前元素,则将当前元素插入在 其后面
        arr[pre_index + 1] = current
    return arr

2. Selection sorting

1. Algorithm idea

Suppose the first element is the comparison element, compare it with the following elements in turn, find the smallest element after comparing all elements, exchange it with the first element, and repeat the above operation. We find the second smallest element and swap it with the element at the second position, and so on to find the remaining smallest element and move it to the front, that is, the sorting is completed.

2. Code implementation

def selection_sort(arr):
    #选择排序
    # 第一层for表示循环选择的遍数
    for i in range(len(arr) - 1):
        # 将起始元素设为最小元素
        min_index = i
        # 第二层for表示最小元素和后面的元素逐个比较
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[min_index]:
                # 如果当前元素比最小元素小,则把当前元素角标记为最小元素角标
                min_index = j
        # 查找一遍后将最小元素与起始元素互换
        arr[min_index], arr[i] = arr[i], arr[min_index]
    return arr

3. Bubble sort

1 .Algorithm idea

Start comparing the first and second ones. If the first one is larger than the second one, swap the positions, then compare the second and third ones, and gradually go back. , after the first round, the largest element has been ranked last,

So if the above operation is repeated, the second largest element will be ranked second to last. , then repeat the above operation n-1 times to complete the sorting, because there is only one element in the last time, so no comparison is needed.

2. Code implementation

def bubble_sort(arr):
    #冒泡排序
    # 第一层for表示循环的遍数
    for i in range(len(arr) - 1):
        # 第二层for表示具体比较哪两个元素
        for j in range(len(arr) - 1 - i):
            if arr[j] > arr[j + 1]:
                # 如果前面的大于后面的,则交换这两个元素的位置
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

4. Quick sort

1. Algorithmic thinking

Find out the baseline conditions, which must be as simple as possible, and continue to decompose (or reduce the size of) the problem until the baseline conditions are met.

2. Code implementation

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

print(quick_sort([10, 5, 2, 3]))

5. Merge sort

1. Algorithm Thought

Merge sort is a typical application of the divide-and-conquer method. Divide-and-Conquer method (pide-and-Conquer): Divide the original problem into n smaller sub-problems with similar structures to the original problem; solve these problems recursively, and then combine the results to obtain the solution to the original problem. The decomposed sequence looks like a binary tree.

Specific implementation steps:

  1. Use recursion to divide the source sequence into multiple sub-sequences using the dichotomy method

  2. Apply for space to divide the two Sort and merge sub-columns and then return

  3. Merge all sub-columns step by step and finally complete the sorting

  4. Note: Decompose first and then merge

2. Code implementation

def merge_sort(arr):
    #归并排序
    if len(arr) == 1:
        return arr
    # 使用二分法将数列分两个
    mid = len(arr) // 2
    left = arr[:mid]
    right = arr[mid:]
    # 使用递归运算
    return marge(merge_sort(left), merge_sort(right))


def marge(left, right):
    #排序合并两个数列
    result = []
    # 两个数列都有值
    while len(left) > 0 and len(right) > 0:
        # 左右两个数列第一个最小放前面
        if left[0] <= right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    # 只有一个数列中还有值,直接添加
    result += left
    result += right
    return result

6. Hill sorting

1. Algorithm idea

The overall idea of ​​Hill sorting is to sort several elements at a fixed interval and then reduce the interval. In this way, the final sequence becomes a basic ordered sequence.

Specific steps:

  1. Calculate an incremental (interval) value

  2. Compare elements with incremental elements, For example, if the increment value is 7, then insert sort the 0, 7, 14, 21... elements

  3. and then sort the 1, 8, 15... elements in ascending order.

  4. After all elements are sorted, reduce the increment to, for example, 3, and then repeat steps 2 and 3 above

  5. Finally reduce the increment By 1, the sequence is basically in order, and the last ordinary insertion can be done

2. Code implementation

def shell_sort(arr):
    #希尔排序
    # 取整计算增量(间隔)值
    gap = len(arr) // 2
    while gap > 0:
        # 从增量值开始遍历比较
        for i in range(gap, len(arr)):
            j = i
            current = arr[i]
            # 元素与他同列的前面的每个元素比较,如果比前面的小则互换
            while j - gap >= 0 and current < arr[j - gap]:
                arr[j] = arr[j - gap]
                j -= gap
            arr[j] = current
        # 缩小增量(间隔)值
        gap //= 2
    return arr

7. Radix sort

1. Algorithm idea

Radix sort (radix sort) belongs to "distribution sort", Also known as "bucket sort" or bin sort, as the name suggests, it allocates the elements to be sorted into certain "buckets" through part of the key value information to achieve the sorting effect. Radix sorting method It is a stable sorting, and its time complexity is O (nlog(r)m), where r is the radix taken, and m is the number of heaps. At some times, the radix sorting method is more efficient than other stable methods. Sexual ranking method.

2. Code implementation

2.1 is transformed from bucket sorting, bucket sorting from the lowest bit to the highest bit, and finally outputs the final ranked list.

def RadixSort(list,d):
    for k in range(d):#d轮排序
        # 每一轮生成10个列表
        s=[[] for i in range(10)]#因为每一位数字都是0~9,故建立10个桶
        for i in list:
            # 按第k位放入到桶中
            s[i//(10**k)%10].append(i)
        # 按当前桶的顺序重排列表
        list=[j for i in s for j in i]
    return list

2.2 Simple implementation

from random import randint
def radix_sort():
  A = [randint(1, 99999999) for _ in xrange(9999)]
  for k in xrange(8):
    S = [ [] for _ in xrange(10)]
    for j in A:
      S[j / (10 ** k) % 10].append(j)
    A = [a for b in S for a in b]
  for i in A:
    print i

八、计数排序

1.算法思想

对每一个输入元素x,确定小于x的元素个数。利用这一信息,就可以直接把x 放在它在输出数组上的位置上了,运行时间为O(n),但其需要的空间不一定,空间浪费大。

2.代码实现

from numpy.random import randint
def Conuting_Sort(A):
    k = max(A)          # A的最大值,用于确定C的长度
    C = [0]*(k+1)       # 通过下表索引,临时存放A的数据
    B = (len(A))*[0]    # 存放A排序完成后的数组
    for i in range(0, len(A)):
        C[A[i]] += 1    # 记录A有哪些数字,值为A[i]的共有几个
    for i in range(1, k+1):
        C[i] += C[i-1]  # A中小于i的数字个数为C[i]
    for i in range(len(A)-1, -1, -1):
        B[C[A[i]]-1] = A[i] # C[A[i]]的值即为A[i]的值在A中的次序
        C[A[i]] -= 1    # 每插入一个A[i],则C[A[i]]减一
    return B

九、堆排序

1.算法思想

堆分为最大堆和最小堆,是完全二叉树。堆排序就是把堆顶的最大数取出,将剩余的堆继续调整为最大堆,具体过程在第二块有介绍,以递归实现 ,

剩余部分调整为最大堆后,再次将堆顶的最大数取出,再将剩余部分调整为最大堆,这个过程持续到剩余数只有一个时结束。

2.代码实现

import time,random
def sift_down(arr, node, end):
    root = node
    #print(root,2*root+1,end)
    while True:
        # 从root开始对最大堆调整
        child = 2 * root +1  #left child
        if child  > end:
            #print(&#39;break&#39;,)
            break
        print("v:",root,arr[root],child,arr[child])
        print(arr)
        # 找出两个child中交大的一个
        if child + 1 <= end and arr[child] < arr[child + 1]: #如果左边小于右边
            child += 1 #设置右边为大
        if arr[root] < arr[child]:
            # 最大堆小于较大的child, 交换顺序
            tmp = arr[root]
            arr[root] = arr[child]
            arr[child]= tmp
            # 正在调整的节点设置为root
            #print("less1:", arr[root],arr[child],root,child)
            root = child #
            #[3, 4, 7, 8, 9, 11, 13, 15, 16, 21, 22, 29]
            #print("less2:", arr[root],arr[child],root,child)
        else:
            # 无需调整的时候, 退出
            break
    #print(arr)
    print(&#39;-------------&#39;)
 
def heap_sort(arr):
    # 从最后一个有子节点的孩子还是调整最大堆
    first = len(arr) // 2 -1
    for i in range(first, -1, -1):
        sift_down(arr, i, len(arr) - 1)
    #[29, 22, 16, 9, 15, 21, 3, 13, 8, 7, 4, 11]
    print(&#39;--------end---&#39;,arr)
    # 将最大的放到堆的最后一个, 堆-1, 继续调整排序
    for end in range(len(arr) -1, 0, -1):
        arr[0], arr[end] = arr[end], arr[0]
        sift_down(arr, 0, end - 1)
        #print(arr)

十、桶排序

1.算法思想

为了节省空间和时间,我们需要指定要排序的数据中最小以及最大的数字的值,来方便桶排序算法的运算。

2.代码实现

#桶排序
def bucket_sort(the_list):
    #设置全为0的数组
    all_list = [0 for i in range(100)]
    last_list = []
    for v in the_list:
        all_list[v] = 1 if all_list[v]==0 else all_list[v]+1
    for i,t_v in enumerate(all_list):
        if t_v != 0:
            for j in range(t_v):
                last_list.append(i)
    return last_list

 总结:

在编程中,算法都是相通的,算法重在算法思想,相当于将一道数学上的应用题的每个条件,区间,可能出现的结果进行分解,分步骤的实现它。算法就是将具体问题的共性抽象出来,将步骤用编程语言来实现。通过这次对排序算法的整理,加深了对各算法的了解,具体的代码是无法记忆的,通过对算法思想的理解,根据伪代码来实现具体算法的编程,才是真正了解算法。

推荐学习:Python视频教程

The above is the detailed content of What are the python sorting algorithms?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete