当前位置:网站首页>Recursion: quick sort, merge sort and heap sort
Recursion: quick sort, merge sort and heap sort
2022-07-03 03:32:00 【My family Dabao is the cutest】
Quick sort
The idea of quick sorting is very simple , Look for any element as a pacesetter , Then use the double pointer to move from left to right ,
- First, let the right pointer point to the end of the array
R=len(arr)-1
, Then judge whether it is equal to the pacesetter element , If it is greater than, the right pointer will continue to move to the left , namelyR -=1
, Until you find a position smaller than the pacesetter - Then let the left pointer point to the beginning of the array , Then judge whether it is less than or equal to the pacesetter element , If it is less than, the pointer will continue to move to the right , namely
L += 1
, Until we find the position of the feather pacesetter - Finally, exchange two elements , Put the large element on the right , Put small elements on the left . The left and right pointers continue , Until the two hands meet
You can see that quick sorting is actually an operation of continuous exchange , After one round of operation , Then perform the same operation on the left and right data , Turn a big problem into a small one , So the recursive algorithm is used for fast sorting .
There are two points in quick row that are very easy to make mistakes
When compared with the pacesetter, the equal sign is included . This is because many data in the array may be the same as the pacesetter , In fact, the same elements as pacesetters can be placed on the left and right , Anyway, after the final sorting, it will be adjacent to the pacesetter . And it can also avoid falling into a dead cycle . For example, the following array , If you don't add an equal sign , You'll find that l and r Will not change .
The outermost loop is easier to understand , requirement
i<j
, Ifl==r
Just go straight back , There's no need to sort , But there is still one in the inner circlei<j
, Why is that ? Mainly to prevent the array from crossing the boundaryWhen i And j On equal terms , This round of exchange is over , Then exchange this element with the pacesetter element , The pacesetter element is where he should be .
It is easier to understand quick sort from the perspective of binary tree , The first is to find the root node , Then divide the data into two parts according to the root node , The left side is less than or equal to the root node , The right side is greater than or equal to the root node . Then recurse down continuously .
Here's an optimization , Is to use random selection pivot, In this way, it can also have good performance in the original incremental array . If it was originally a sorted arr, Then it will degenerate into O ( n 2 ) O(n^2) O(n2).
def quickSort(arr, l, r):
if l >= r: # Recursion ends
return
pivot_idx = random.randint(l, r) # Random selection pivot
arr[l], arr[pivot_idx] = arr[pivot_idx], arr[l] # pivot Place to the far left
pivot = arr[l] # Select the leftmost as pivot
i, j = l, r # Double pointer
while i < j:
while i<j and arr[j] >= pivot: # Find the first one on the right <pivot The elements of
j -= 1
while i<j and arr[i] <= pivot: # Find the first one on the left >pivot The elements of
i += 1
arr[i],arr[j] = arr[j],arr[i] # And move it to right It's about
arr[l],arr[i] = arr[i],pivot
quickSort(arr, l, i-1) # Recursive pair mid Sort the elements on both sides
quickSort(arr, i+1, r)
quickSort(arr, 0, len(arr)-1) # Call the quick sorting function pair nums Sort
return nums
Merge sort
The bottom layer of merge sort is also recursive thinking , In fact, root quicksort is very similar . Merge sort has two points
- We divide the array into two , Left and right . If we arrange on the left , Then the right side is also in order , At this time, you only need to combine the two sub arrays into one . So how to sort the left and right arrays ? Let's first look at the array on the left , We also divide the array on the left into two parts , If these two parts are in good order , We can merge directly . Now you can see that , We put the big sorting problem , It is transformed into the sorting problem and merging problem of each word part .
This process is very simple to write recursively
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
def mergesort(arr, l, r):
if l >= r:
return
m = (l + r) // 2
mergesort(arr,l,m) # Left half sort
mergesort(arr,m+1,r) # Sort the right half
# Arrange the left and right parts of the order before merging
# The range of the array on the left is l~m
# The range of the array on the right is m+1~r
# Now is to merge these two ordered arrays
i,j = l,m+1
tmp = []
while i <= m and j <= r:
if arr[i] < arr[j]:
tmp.append(arr[i])
i += 1
else:
tmp.append(arr[j])
j += 1
tmp += arr[i:m+1]
tmp += arr[j:r+1]
for k in range(l,r+1):
arr[k] = tmp[k-l]
mergesort(nums, 0, len(nums)-1) # Call the quick sorting function pair nums Sort
return nums
边栏推荐
- Captura下载安装及在Captura配置FFmpeg
- Node start server
- Idea set method call ignore case
- Application of derivative in daily question
- PAT乙级“1104 天长地久”DFS优化思路
- 基于Qt的yolov5工程
- Nanning water leakage detection: warmly congratulate Guangxi Zhongshui on winning the first famous brand in Guangxi
- Pytoch lightweight visualization tool wandb (local)
- C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
- 为什么线程崩溃不会导致 JVM 崩溃
猜你喜欢
Captura下载安装及在Captura配置FFmpeg
ffmpeg录制屏幕和截屏
Hi3536C V100R001C02SPC040 交叉编译器安装
LVGL使用心得
The series of hyperbolic function in daily problem
PHP generates PDF tcpdf
Table structure of Navicat export database
Positioning (relative positioning, absolute positioning, fixed positioning, Z-index) 2022-2-11
Elsevier latex submitted the article pdftex def Error: File `thumbnails/cas-email. jpeg‘ not found: using draf
用Three.js做一个简单的3D场景
随机推荐
Converts a timestamp to a time in the specified format
The XML file generated by labelimg is converted to VOC format
Yolov5 project based on QT
Positioning (relative positioning, absolute positioning, fixed positioning, Z-index) 2022-2-11
Réglez la hauteur et lancez le système. Currenttimemillis catton
递归:深度优先搜索
Applet get user avatar and nickname
ffmpeg录制屏幕和截屏
MongoDB简介
900w+ data, from 17s to 300ms, how to operate
Solve high and send system Currenttimemillis Caton
PAT乙级“1104 天长地久”DFS优化思路
Section 26 detailed explanation and demonstration of IPSec virtual private network configuration experiment - simulation experiment based on packettracer8.0
Gavin teacher's perception of transformer live class - rasa project's actual banking financial BOT Intelligent Business Dialogue robot architecture, process and phenomenon decryption through rasa inte
Model transformation onnx2engine
Stepping on pits and solutions when using inputfilter to limit EditText
机械臂速成小指南(八):运动学建模(标准DH法)
VS 2019 配置tensorRT生成engine
Idea format code idea set shortcut key format code
Mongodb replication set [master-slave replication]