当前位置:网站首页>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
边栏推荐
- 为什么线程崩溃不会导致 JVM 崩溃
- 递归使用和多维数组对象变一维数组对象
- 动态规划:最长回文子串和子序列
- 403 error displayed when vs cloning
- Elsevier latex submitted the article pdftex def Error: File `thumbnails/cas-email. jpeg‘ not found: using draf
- numpy之 警告VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
- Convert binary stream to byte array
- Bigvision code
- Solve high and send system Currenttimemillis Caton
- Makefile demo
猜你喜欢
MySQL practice 45 lecture [transaction isolation]
Table structure of Navicat export database
Vs 2019 configuration tensorrt
Avec trois. JS fait une scène 3D simple
[MySQL] the difference between left join, right join and join
[pyg] understand the messagepassing process, GCN demo details
C programming learning notes [edited by Mr. Tan Haoqiang] (Chapter III sequence programming) 05 data input and output
用Three.js做一个简单的3D场景
Summary of determinant knowledge points in Chapter 1 of Linear Algebra (Jeff's self perception)
UMI route interception (simple and rough)
随机推荐
MongoDB简介
BigVision代码
[leetcode question brushing day 34] 540 Unique element in array, 384 Disrupt array, 202 Happy number, 149 Maximum number of points on a line
Hi3536c v100r001c02spc040 cross compiler installation
900W+ 数据,从 17s 到 300ms,如何操作
Numpy warning visibledeprecationwarning: creating an ndarray from ragged needed sequences
PAT乙级“1104 天长地久”DFS优化思路
File rename
递归使用和多维数组对象变一维数组对象
动态规划:最长公共子串和最长公共子序列
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post
递归:深度优先搜索
VS 2019 配置tensorRT生成engine
Limit of one question per day
Compare float with 0
Pytoch configuration
Avec trois. JS fait une scène 3D simple
Some preliminary preparations for QQ applet development: make an appointment for a development account, download and install developer tools, and create QQ applet
VS 2019安装及配置opencv
[mathematical logic] propositional logic (propositional logic reasoning | formal structure of reasoning | inference law | additional law | simplification law | hypothetical reasoning | refusal | disju