当前位置:网站首页>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==rJust 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
边栏推荐
- labelimg生成的xml文件转换为voc格式
- [combinatorics] brief introduction to generating function (definition of generating function | Newton binomial coefficient | commonly used generating function | correlation with constant | correlation
- Bid farewell to artificial mental retardation: Mengzi open source project team received RMB 100 million financing to help NLP develop
- Don't use the new Dede collection without the updated Dede plug-in
- [embedded module] OLED display module
- QQ小程序开发之 一些前期准备:预约开发账号、下载安装开发者工具、创建qq小程序
- Change and access of median value of listening object
- Pytorch轻量级可视化工具wandb(local)
- redis高级应用【密码防护、数据持久化、主从同步、哨兵模式、事务】【暂未完成(半成品)】
- Nce detail of softmax approximation
猜你喜欢
![C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output](/img/38/9c460fc58b62609dd02e7c61207ae6.jpg)
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output
![MySQL practice 45 lecture [transaction isolation]](/img/a5/5420651d6be51e892976f02be8c43c.png)
MySQL practice 45 lecture [transaction isolation]

UMI route interception (simple and rough)

FileZilla Client下載安裝
![[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)](/img/19/815e7cba81f6eb52db5ef0db556dfd.jpg)
[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)

Mysql Mac版下载安装教程

递归:一维链表和数组

umi 路由拦截(简单粗暴)
![Learning notes of C programming [compiled by Mr. Tan Haoqiang] (Chapter III sequence programming) 04 C sentence](/img/60/bae0e8d92a53bcd2b2de3fb22b3b99.jpg)
Learning notes of C programming [compiled by Mr. Tan Haoqiang] (Chapter III sequence programming) 04 C sentence

Pytorch轻量级可视化工具wandb(local)
随机推荐
900w+ data, from 17s to 300ms, how to operate
小程序获取用户头像和昵称
基于Qt的yolov5工程
[combinatorics] brief introduction to generating function (definition of generating function | Newton binomial coefficient | commonly used generating function | correlation with constant | correlation
C # webrequest post mode, based on "basic auth" password authentication mode, uploads files and submits other data using multipart / form data mode
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post
Positioning (relative positioning, absolute positioning, fixed positioning, Z-index) 2022-2-11
将时间戳转为指定格式的时间
Vs 2019 configure tensorrt to generate engine
softmax的近似之NCE详解
Pytorch轻量级可视化工具wandb(local)
ffmpeg之 一张/多张图片合成视频
shardingsphere动态数据源
Limit of one question per day
docker安装及启动mysql服务
解决高並發下System.currentTimeMillis卡頓
Using jasmine to monitor constructors - spying on a constructor using Jasmine
Bid farewell to artificial mental retardation: Mengzi open source project team received RMB 100 million financing to help NLP develop
umi 路由拦截(简单粗暴)
Hi3536C V100R001C02SPC040 交叉编译器安装