Quick sort is actually a pre-order traversal of a binary tree, and merge sort is actually a post-order traversal of a binary tree.
The logic of quick sort is that to sort nums[lo..hi]
, we first find a dividing point p
, and make nums[lo..p-1]
less than or equal to nums[p]
by exchanging elements, and nums[p+1..hi]
is greater than nums[p]
, and then recursively go to nums[lo..p-1]
and nums[p+1..hi]
, and finally the entire array is sorted.
The code framework of quick sort is as follows:
void sort(int[] nums, int lo, int hi) {
/****** 前序遍历位置 ******/
// 通过交换元素构建分界点 p
int p = partition(nums, lo, hi);
/************************/
sort(nums, lo, p - 1);
sort(nums, p + 1, hi);
}
First construct the demarcation point, and then go to the left and right subarrays to construct the demarcation point, don't you think this is a preorder traversal of a binary tree?
Let's talk about the logic of merge sort. To sort nums[lo..hi]
, we first sort nums[lo..mid]
, then sort nums[mid+1..hi]
, and finally merge these two ordered subarrays, and the entire array is sorted.
The code framework of merge sort is as follows:
void sort(int[] nums, int lo, int hi) {
int mid = (lo + hi) / 2;
// 排序 nums[lo..mid]
sort(nums, lo, mid);
// 排序 nums[mid+1..hi]
sort(nums, mid + 1, hi);
/****** 后序位置 ******/
// 合并 nums[lo..mid] 和 nums[mid+1..hi]
merge(nums, lo, mid, hi);
/*********************/
}
Sort the left and right subarrays first, and then merge them (similar to the logic of merging ordered linked lists). Do you think this is a post-order traversal framework for binary trees? In addition, isn't this the legendary divide and conquer algorithm, but that's it
Having said so much, the purpose is to show that the algorithm idea of binary tree is widely used, and it can even be said that as long as recursion is involved, it can be abstracted into the problem of binary tree.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。