Home Backend Development Python Tutorial Top ten sorting algorithms that programmers must master (Part 1)

Top ten sorting algorithms that programmers must master (Part 1)

Aug 15, 2023 pm 02:55 PM
Sorting Algorithm



#Book Issue Introduction

Sort AlgorithmIt can be said that every programmer must have it After mastering, it is necessary to understand their principles and implementation.The following is an introduction to the Python implementation of the ten most commonly used sorting algorithms to facilitate your learning. .


01 Bubble sort——exchange sort02 Quick sort—— Exchange sorting

03 Selection sort——Selection sorting04 Heap sort ——Select class sort

05 Insertion sort——Insertion class sort

06 Hill sorting-insertion sorting

07 Merging sort-merging sorting

08 Counting sorting-distribution sorting

09 Radix sorting-distribution sorting

10 Bucket sorting-distribution sorting



01
##risk Bubble Sort
#Bubble Sort:
A classic sorting algorithm gets its name because during the operation of the algorithm, extreme values ​​will gradually emerge like bubbles under the water.

Algorithm principle:
Compare adjacent elements. If the first one is bigger than the second one, swap them both.
  • Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. At this point, the last element should be the largest number.
  • Repeat the above steps for all elements except the last one.
  • Continue repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

code show as below:
'''冒泡排序'''
def Bubble_Sort(arr):
    for i in range(1, len(arr)):
        for j in range(0, len(arr)-i):
            if arr[j] > arr[j+1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

arr = [29, 63, 41, 5, 62, 66, 57, 34, 94, 22]
result = Bubble_Sort(arr)
print('result list: ', result)
# result list: [5, 22, 29, 34, 41, 57, 62, 63, 66, 94]
Copy after login

##02
Quick Sort
Quicksort: Split the data to be sorted into two independent parts through one sort, and then Then use this method to quickly sort the two parts of the data respectively. The entire sorting process can be performed recursively, so that the entire data becomes an ordered sequence, which is an improvement on the bubble sort algorithm.

Algorithm principle:
  • First set a dividing value, and divide the array into left and right parts through this dividing value.

  • Collect the data that is greater than or equal to the cut-off value to the right of the array, and the data that is less than the cut-off value are concentrated to the left of the array. At this time, each element in the left part is less than or equal to the dividing value, and each element in the right part is greater than or equal to the dividing value.

  • #Then, the data on the left and right can be sorted independently. For the array data on the left, you can take a dividing value and divide this part of the data into left and right parts. Similarly, place the smaller value on the left and the larger value on the right. The array data on the right can also be processed similarly.

  • # Repeat the above process until the data in the left and right parts are sorted.


code show as below:
'''快速排序'''
def Quick_Sort(arr):
    # 递归入口及出口
    if len(arr) >= 2:
        # 选取基准值,也可以选取第一个或最后一个元素
        mid = arr[len(arr) // 2]
        # 定义基准值左右两侧的列表
        left, right = [], []
        # 从原始数组中移除基准值
        arr.remove(mid)
        for num in arr:
            if num >= mid:
                right.append(num)
            else:
                left.append(num)
        return Quick_Sort(left) + [mid] + Quick_Sort(right)
    else:
        return arr

arr = [27, 70, 34, 65, 9, 22, 47, 68, 21, 18]
result = Quick_Sort(arr)
print('result list: ', result)
# result list: [9, 18, 21, 22, 27, 34, 47, 65, 68, 70]
Copy after login


#03
Select sort
##Selection sort : It is a simple and intuitive sorting algorithm. No matter what data is entered, the time complexity is O(n²). So when using it, the smaller the data size, the better.

Algorithm principle:
    Find the smallest (large) element in the unsorted sequence and store it at the starting position of the sorted sequence.
  • Continue to find the smallest (largest) element from the remaining unsorted elements, and then put it at the end of the sorted sequence.
  • And so on until all elements are sorted.

代码如下:
'''选择排序'''
def Selection_Sort(arr):
    for i in range(len(arr) - 1):
        # 记录最小数的索引
        minIndex = i
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[minIndex]:
                minIndex = j
        # i 不是最小数时,将 i 和最小数进行交换
        if i != minIndex:
            arr[i], arr[minIndex] = arr[minIndex], arr[i]
    return arr

arr = [5, 10, 76, 55, 13, 79, 49, 51, 65, 30]
result = Quick_Sort(arr)
print(&#39;result list: &#39;, result)
# result list: [5, 10, 13, 30, 49, 51, 55, 65, 76, 79]
Copy after login

04
插入排序
插入排序(Insertion Sort)一般也被称为直接插入排序,是一种最简单直观的排序算法

算法原理:
  • 将第一待排序序列第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。

  • 从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。


代码如下:
&#39;&#39;&#39;插入排序&#39;&#39;&#39;
def Insertion_Sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr

arr = [31, 80, 42, 47, 35, 26, 10, 5, 51, 53]
result = Insertion_Sort(arr)
print(&#39;result list: &#39;, result)
# result list: [5, 10, 26, 31, 35, 42, 47, 51, 53, 80]
Copy after login

05
堆排序
堆排序(Heap sort):是指利用堆这种数据结构所设计的一种排序算法,堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。堆排序可以说是一种利用堆的概念来排序的选择排序。

算法原理:
  • 创建一个堆 H[0……n-1];

  • 把堆首(最大值)和堆尾互换;

  • 把堆的尺寸缩小 1,并调用 shift_down(0),目的是把新的数组顶端数据调整到相应位置;

  • 重复步骤 2,直到堆的尺寸为 1。


代码如下:
&#39;&#39;&#39;堆排序&#39;&#39;&#39;
def Heapify(arr, n, i):
    largest = i
    # 左右节点分块
    left = 2 * i + 1
    right = 2 * i + 2
    if left < n and arr[i] < arr[left]:
        largest = left
    if right < n and arr[largest] < arr[right]:
        largest = right
    if largest != i:
        # 大小值交换
        arr[i], arr[largest] = arr[largest], arr[i]
        # 递归
        Heapify(arr, n, largest)

def Heap_Sort(arr):
    nlen = len(arr)
    for i in range(nlen, -1, -1):
        # 调整节点
        Heapify(arr, nlen, i)
    for i in range(nlen - 1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i]
        # 调整节点
        Heapify(arr, i, 0)
    return arr

arr = [26, 53, 83, 86, 5, 46, 72, 21, 4, 75]
result = Heap_Sort(arr)
print(&#39;result list: &#39;, result)
# result list: [4, 5, 21, 26, 46, 53, 72, 75, 83, 86]
Copy after login

The above is the detailed content of Top ten sorting algorithms that programmers must master (Part 1). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Complex experimental design issues in Kuaishou's two-sided market Complex experimental design issues in Kuaishou's two-sided market Apr 15, 2023 pm 07:40 PM

1. Background of the problem 1. Introduction to the two-sided market experiment The two-sided market, that is, a platform, includes two participants, producers and consumers, and both parties promote each other. For example, Kuaishou has a video producer and a video consumer, and the two identities may overlap to a certain extent. Bilateral experiment is an experimental method that combines groups on the producer and consumer sides. Bilateral experiments have the following advantages: (1) The impact of the new strategy on two aspects can be detected simultaneously, such as changes in product DAU and the number of people uploading works. Bilateral platforms often have cross-side network effects. The more readers there are, the more active the authors will be, and the more active the authors will be, the more readers will follow. (2) Effect overflow and transfer can be detected. (3) Help us better understand the mechanism of action. The AB experiment itself cannot tell us the relationship between cause and effect, only

How to filter and sort data in Vue technology development How to filter and sort data in Vue technology development Oct 09, 2023 pm 01:25 PM

How to filter and sort data in Vue technology development In Vue technology development, data filtering and sorting are very common and important functions. Through data filtering and sorting, we can quickly query and display the information we need, improving user experience. This article will introduce how to filter and sort data in Vue, and provide specific code examples to help readers better understand and use these functions. 1. Data filtering Data filtering refers to filtering out data that meets the requirements based on specific conditions. In Vue, we can pass comp

Google uses AI to break the ten-year ranking algorithm seal. It is executed trillions of times every day, but netizens say it is the most unrealistic research? Google uses AI to break the ten-year ranking algorithm seal. It is executed trillions of times every day, but netizens say it is the most unrealistic research? Jun 22, 2023 pm 09:18 PM

Organizing | Nuka-Cola, Chu Xingjuan Friends who have taken basic computer science courses must have personally designed a sorting algorithm - that is, using code to rearrange the items in an unordered list in ascending or descending order. It's an interesting challenge, and there are many possible ways to do it. A lot of time has been invested in figuring out how to accomplish sorting tasks more efficiently. As a basic operation, sorting algorithms are built into the standard libraries of most programming languages. There are many different sorting techniques and algorithms used in code bases around the world to organize large amounts of data online, but at least as far as the C++ libraries used with the LLVM compiler are concerned, the sorting code has not changed in more than a decade. Recently, the Google DeepMindAI team has now developed a

How to use radix sort algorithm in C++ How to use radix sort algorithm in C++ Sep 19, 2023 pm 12:15 PM

How to use the radix sort algorithm in C++ The radix sort algorithm is a non-comparative sorting algorithm that completes sorting by dividing the elements to be sorted into a limited set of digits. In C++, we can use the radix sort algorithm to sort a set of integers. Below we will discuss in detail how to implement the radix sort algorithm, with specific code examples. Algorithm idea The idea of ​​the radix sorting algorithm is to divide the elements to be sorted into a limited set of digital bits, and then sort the elements on each bit in turn. Sorting on each bit is completed

How to implement the selection sort algorithm in C# How to implement the selection sort algorithm in C# Sep 20, 2023 pm 01:33 PM

How to implement the selection sort algorithm in C# Selection sort (SelectionSort) is a simple and intuitive sorting algorithm. Its basic idea is to select the smallest (or largest) element from the elements to be sorted each time and put it at the end of the sorted sequence. Repeat this process until all elements are sorted. Let's learn more about how to implement the selection sort algorithm in C#, along with specific code examples. Creating a selection sort method First, we need to create a method for implementing selection sort. This method accepts a

Swoole Advanced: How to use multi-threading to implement high-speed sorting algorithm Swoole Advanced: How to use multi-threading to implement high-speed sorting algorithm Jun 14, 2023 pm 09:16 PM

Swoole is a high-performance network communication framework based on PHP language. It supports the implementation of multiple asynchronous IO modes and multiple advanced network protocols. On the basis of Swoole, we can use its multi-threading function to implement efficient algorithm operations, such as high-speed sorting algorithms. The high-speed sorting algorithm (QuickSort) is a common sorting algorithm. By locating a benchmark element, the elements are divided into two subsequences. Those smaller than the benchmark element are placed on the left, and those greater than or equal to the benchmark element are placed on the right. Then the left and right subsequences are placed. subsequence recursion

Discussion on application scenarios of different PHP array sorting algorithms Discussion on application scenarios of different PHP array sorting algorithms Apr 28, 2024 am 09:39 AM

For different scenarios, it is crucial to choose the appropriate PHP array sorting algorithm. Bubble sort is suitable for small-scale arrays without stability requirements; quick sort has the lowest time complexity in most cases; merge sort has high stability and is suitable for scenarios that require stable results; selection sort is suitable for situations without stability requirements. Situation; Heap sort efficiently finds the maximum or minimum value. Through comparison of actual cases, quick sort is superior to other algorithms in terms of time efficiency, but merge sort should be chosen when stability needs to be considered.

What are the sorting algorithms for arrays? What are the sorting algorithms for arrays? Jun 02, 2024 pm 10:33 PM

Array sorting algorithms are used to arrange elements in a specific order. Common types of algorithms include: Bubble sort: swap positions by comparing adjacent elements. Selection sort: Find the smallest element and swap it to the current position. Insertion sort: Insert elements one by one to the correct position. Quick sort: divide and conquer method, select the pivot element to divide the array. Merge Sort: Divide and Conquer, Recursive Sorting and Merging Subarrays.

See all articles