Use python to implement various sorting algorithms
A summary of common centralized sorting algorithms
Merge sort
Merge sort, also called merge sort, is a typical application of the divide-and-conquer method. The idea of divide and conquer is to decompose each problem into small problems, solve each small problem, and then merge them.
The specific merge sort is to recursively decompose a set of unordered numbers into sub-items with only one element by n/2, and one element is already sorted. Then merge these ordered sub-elements.
The process of merging is to compare two sorted subsequences, first select the smallest element in the two subsequences, select the smallest subsequence of the two elements, and remove and add it from the subsequence
to the final result set until the two subsequences are merged.
The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
Stable, time complexity O(nlog n)
Insertion sort
The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Stable, time complexity O(n^2)
To exchange the values of two elements in python, you can write: a, b = b, a. In fact, this is because the left and right sides of the assignment symbol are tuples
(It needs to be emphasized here that in python, tuples In fact, it is delimited by commas "," instead of brackets).
Selection sort
Selection sort is a simple and intuitive sorting algorithm. Here's how it works. First, find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence. Then, continue to find the smallest (large) 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
Unstable, time complexity O(n^2)
Hill sorting
Hill sorting, also called descending incremental sorting algorithm, Hill sorting is a non-stable sorting algorithm. This method is also called reducing incremental sorting, because DL. Shell was named after it was proposed in 1959.
First take an integer d1 less than n as the first increment, and divide all records in the file into d1 groups. All records whose distance is a multiple of d1 are placed in the same group. First sort within each group;
Then, take the second increment d2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Unstable, time complexity average time O(nlogn) worst time O(n^s)1
Heap Sort (Heap Sort)
The definition of "heap": in In the "heap" with a starting index of 0:
The right child node of node i is at position 2 * i + 24) The parent node of node i is at position floor( (i - 1) / 2) : Note that floor means "take "Full" operation
Characteristics of the heap:
The key value of each node must always be greater than (or less than) its parent node
"Max Heap":
The root node of the "heap" saves the maximum key value node. That is, the key value of each node in the "heap" is always greater than its child nodes.
Move up, move down:
When the key value of a node is greater than its parent node, then we have to perform a "move up" operation, that is, we move the node to the position of its parent node,
Let its parent node move to its position, and then we continue to judge the node and do not stop "moving up" until the node is no longer larger than its parent node.
Now let’s learn more about the “move down” operation. When we change the key value of a node to a smaller value, we need to "move it down".
Method:
We first build a maximum heap (time complexity O(n)), and then each time we only need to exchange the root node with the node at the last position, and then exclude the last position, and then After the exchange, the heap of the root node is adjusted (time complexity O(lgn)), that is, the root node can be "moved down". The total time complexity of heap sort is O(nlgn).
The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
Unstable, time complexity O(nlog n)
Quick sort
Quick sort algorithm and merge sort algorithm Likewise, it is also based on the divide-and-conquer model. The three steps of the divide-and-conquer process of quick sorting the subarray A[p...r] are:
Decomposition: Divide the array A[p...r] into A[p...q-1] and A[q+1...r] two parts, where each element in A[p...q-1] is less than or equal to A[q] and each element in A[q+1...r] elements are greater than or equal to A[q];
Solution: Sort the subarrays A[p...q-1] and A[q+1...r] by recursively calling quick sort;
Merge : Because the two subarrays are sorted in place, no additional operations are required.
For the beginning of each iteration of partition partition, x=A[r], for any array subscript k, there are:
1) If p≤k≤i, then A[k]≤x.
2) If i+1≤k≤j-1, then A[k]>x.
3) If k=r, then A[k]=x.
The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
Unstable, the best time complexity is O(nlogn) and the worst time is O(n^2)
Let’s talk about sequences in python:
Lists, tuples and strings are all sequences, but what are sequences? Why is it so special? The two main features of sequences are the indexing operator and the slicing operator. The index operator allows us to grab a specific item from a sequence. The slice operator allows us to obtain a slice of the sequence, that is, a part of the sequence, such as: a = ['aa','bb','cc'], print a[0] is an index operation, print a[0:2] for slicing operations.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.
