Imagine that you have a piece of paper in your hand with 1,000 names listed and you need to find one of them, but this list is not in alphabetical order. It would be very frustrating, isn't it? While it takes a long time to sort out this list, it makes finding names much easier. So sorting things is our human natural desire, and searching for sorted lists is obviously more labor-saving than searching for unordered lists.
In the computer world, the list of searches can be very large, and even fast computers, performance may be affected. In this case, a suitable sorting and search algorithm would be the solution to such problems. Sort is the process of sorting a list of values ??in order, while search is the process of finding the position of values ??in the list.
To illustrate the importance of this issue, let me show you what the great American computer scientist Donald Knuth said:
Computer manufacturers in the 1960s estimated that, given all customers, more than 25% of their computer runtime was spent on sorting. In fact, in many installation cases, the sorting task takes up more than half of the calculation time. From these statistics, we can conclude that (i) sorting has many important applications, or (ii) many people sort when they shouldn't, or (iii) inefficient sorting algorithms have been widely used. ——"The Art of Computer Programming" Volume 3: Sort and Search, Page 3
In this tutorial, I will show you how to implement the selection sorting algorithm and the linear search algorithm.
But before we get started, if you just want to sort and search in your Python code, I'll show you the built-in method.
Built-in sorting methods and functions in Python
You can create many sorting algorithms using Python. This is a good learning exercise, but for production applications you should stick with built-in stored functions and methods in Python.
Python has a list.sort()
method that you can use to sort the list in-place. The sorting algorithm used behind the scenes of Python is called Timsort. It is a hybrid sorting algorithm based on insert sorting and merge sorting that provides excellent performance in many real-life lives. Here is an example of how to use these two functions and methods:
marks_a = [61, 74, 58, 49, 95, 88] marks_b = [94, 85, 16, 47, 88, 59] # [49, 58, 61, 74, 88, 95] print(sorted(marks_a)) # None print(marks_b.sort()) # [61, 74, 58, 49, 95, 88] print(marks_a) # [16, 47, 59, 85, 88, 94] print(marks_b)
You may notice some of the situations in the above code. The sorted()
function returns a new sorted list without changing the original list marks_a
. However, the original list remains the same. On the other hand, when we call the marks_b
method on sort()
, it returns None
.
You can pass some parameters to modify the sorting behavior. For example, pass a function to the reverse
parameter, which sorts our list of words alphabetically without any parameters. In the second case, we use sorted()
to reverse the order of sorted words. reverse=True
Select sortThe algorithm is based on continuous selection of the minimum or maximum value. Suppose we have a list that we want to sort in ascending order (small to large). The smallest element will be at the beginning of the list and the largest element will be at the end of the list.
Suppose the original list looks like this:
| 7 | 5 | 3.5 | 4 | 3.1 |
minimum value in the list, in this case . 3.1
. That is, exchange with . The list will now look like this: 3.1
7
| 3.1 | 5 | 3.5 | 4 | 7 |
Now that we determine the correct position of the first element in the list, we repeat the above steps (find the minimum value) from the second
. So we will now exchange with . The list now becomes: 3.5
3.5
5
At this point, we make sure that the first element and the second element are in their correct position. | 3.1 | 3.5 | 5 | 4 | 7 |
. The minimum value in the rest of the list is
, which we now swap with. Therefore, the list becomes: 5
4
5
Therefore, we now determine that the first three | 3.1 | 3.5 | 4 | 5 | 7 |
elements are in the correct position and the process continues in this way.
Let's see how to implement the selection sorting algorithm in Python (based on Isai Damier):
Let's test the algorithm by adding the following statement at the end of the above script:
marks_a = [61, 74, 58, 49, 95, 88] marks_b = [94, 85, 16, 47, 88, 59] # [49, 58, 61, 74, 88, 95] print(sorted(marks_a)) # None print(marks_b.sort()) # [61, 74, 58, 49, 95, 88] print(marks_a) # [16, 47, 59, 85, 88, 94] print(marks_b)In this case you should get the following output:
def selectionSort(aList): for i in range(len(aList)): least = i for k in range(i+1, len(aList)): if aList[k] < aList[least]: least = k swap(aList, least, i) def swap(A, x, y): temp = A[x] A[x] = A[y] A[y] = temp
Linear search algorithm
[4.6, 4.7, 5.76, 7.3, 7.6, 25.3, 32.4, 43.5, 52.3, 55.3, 86.7]
Algorithm is a simple algorithm in which each item in the list is checked (starting from the first item) until the desired item is found or the end of the list is reached.
The linear search algorithm is implemented in Python as follows (based on Python School):
Let's test the code. Enter the following statement at the end of the above Python script:When entering
my_list = [5.76,4.7,25.3,4.6,32.4,55.3,52.3,7.6,7.3,86.7,43.5] selectionSort(my_list) print(my_list), make sure it is between single or double quotes (i.e.
). For example, if you type
, you should get the following output:def linearSearch(item,my_list): found = False position = 0 while position < len(my_list) and not found: if my_list[position] == item: found = True position = position + 1 return found
input
'pencil'
'pencil'
And if you enter
Oops, your item seems not to be in the bag
Conclusion
As we have seen, Python proves itself again as a programming language that is easy to program the concept of algorithms, just like we deal with sorting and search algorithms here.
It should be noted that there are other types of sorting and search algorithms. If you want to dig deeper into these algorithms using Python, you can refer to the free Python object-oriented programming textbook.
The above is the detailed content of Sorting and Searching in?Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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's unittest and pytest are two widely used testing frameworks that simplify the writing, organizing and running of automated tests. 1. Both support automatic discovery of test cases and provide a clear test structure: unittest defines tests by inheriting the TestCase class and starting with test\_; pytest is more concise, just need a function starting with test\_. 2. They all have built-in assertion support: unittest provides assertEqual, assertTrue and other methods, while pytest uses an enhanced assert statement to automatically display the failure details. 3. All have mechanisms for handling test preparation and cleaning: un

PythonisidealfordataanalysisduetoNumPyandPandas.1)NumPyexcelsatnumericalcomputationswithfast,multi-dimensionalarraysandvectorizedoperationslikenp.sqrt().2)PandashandlesstructureddatawithSeriesandDataFrames,supportingtaskslikeloading,cleaning,filterin

Dynamic programming (DP) optimizes the solution process by breaking down complex problems into simpler subproblems and storing their results to avoid repeated calculations. There are two main methods: 1. Top-down (memorization): recursively decompose the problem and use cache to store intermediate results; 2. Bottom-up (table): Iteratively build solutions from the basic situation. Suitable for scenarios where maximum/minimum values, optimal solutions or overlapping subproblems are required, such as Fibonacci sequences, backpacking problems, etc. In Python, it can be implemented through decorators or arrays, and attention should be paid to identifying recursive relationships, defining the benchmark situation, and optimizing the complexity of space.

To implement a custom iterator, you need to define the __iter__ and __next__ methods in the class. ① The __iter__ method returns the iterator object itself, usually self, to be compatible with iterative environments such as for loops; ② The __next__ method controls the value of each iteration, returns the next element in the sequence, and when there are no more items, StopIteration exception should be thrown; ③ The status must be tracked correctly and the termination conditions must be set to avoid infinite loops; ④ Complex logic such as file line filtering, and pay attention to resource cleaning and memory management; ⑤ For simple logic, you can consider using the generator function yield instead, but you need to choose a suitable method based on the specific scenario.

Future trends in Python include performance optimization, stronger type prompts, the rise of alternative runtimes, and the continued growth of the AI/ML field. First, CPython continues to optimize, improving performance through faster startup time, function call optimization and proposed integer operations; second, type prompts are deeply integrated into languages ??and toolchains to enhance code security and development experience; third, alternative runtimes such as PyScript and Nuitka provide new functions and performance advantages; finally, the fields of AI and data science continue to expand, and emerging libraries promote more efficient development and integration. These trends indicate that Python is constantly adapting to technological changes and maintaining its leading position.

Python's socket module is the basis of network programming, providing low-level network communication functions, suitable for building client and server applications. To set up a basic TCP server, you need to use socket.socket() to create objects, bind addresses and ports, call .listen() to listen for connections, and accept client connections through .accept(). To build a TCP client, you need to create a socket object and call .connect() to connect to the server, then use .sendall() to send data and .recv() to receive responses. To handle multiple clients, you can use 1. Threads: start a new thread every time you connect; 2. Asynchronous I/O: For example, the asyncio library can achieve non-blocking communication. Things to note

Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance

The core answer to Python list slicing is to master the [start:end:step] syntax and understand its behavior. 1. The basic format of list slicing is list[start:end:step], where start is the starting index (included), end is the end index (not included), and step is the step size; 2. Omit start by default start from 0, omit end by default to the end, omit step by default to 1; 3. Use my_list[:n] to get the first n items, and use my_list[-n:] to get the last n items; 4. Use step to skip elements, such as my_list[::2] to get even digits, and negative step values ??can invert the list; 5. Common misunderstandings include the end index not
