当前位置:网站首页>On merging and sorting
On merging and sorting
2022-06-25 21:14:00 【Rabbit cloud program】
Interview questions : What are the ideas of quick arrangement and merging based on
answer : Based on the idea of divide and rule
Ideological concept
Merge sort , english MERGE-SORT, utilize Merger Thought , Use the classic Divide and conquer (divide-and-conquer) Strategy to achieve sorting . The essence of this is division and treatment , Many people may be familiar with fast platoon , Bubble and other familiar sorting methods , Not very good at merging and sorting .

You can see that this algorithm is very similar to a complete binary tree , By dividing the data into small piles , Then sort and combine these data , It's a divide and rule strategy . You can also understand it as splitting the item first , Then merge the same items , The final result is what we want .
#include <iostream>void Merge(int r[], int r1[], int s, int m, int t){int i = s;int j = m + 1;int k = s;while (i <= m && j <= t){if (r[i] <= r[j])r1[k++] = r[i++];elser1[k++] = r[j++];}if (i <= m)while (i <= m)r1[k++] = r[i++];elsewhile (j <= t)r1[k++] = r[j++];for (int n = s; n <= t; n++)r[n] = r1[n];}void MergeSort(int r[], int r1[], int s, int t){if (s < t){int m = (s + t) / 2;MergeSort(r, r1, s, m);MergeSort(r, r1, m + 1, t);Merge(r, r1, s, m, t);}}int main(){int r[8] = {10, 3, 5, 1, 9, 34, 54, 565}, r1[8];MergeSort(r, r1, 0, 7);for (int q = 0; q < 8; q++)std::cout << r[q] << std::ends;return 0;}
Algorithm complexity
And the sorting time complexity is O(N*logN), Additional space complexity O(N).
Merge sort comparison takes up memory , But it is an efficient and stable algorithm .

application
Based on quick sort , Make a few adjustments to complete the merging and sorting .
Small and problem

See this problem , An implementation method we can easily think of is : double for Loop traversal , Find a number smaller than the current number , Add up . The time complexity of this method is O(n^2).
def merge_sort(arr):# Recursively decompose the array , When there is only one element left , Stop decomposingif len(arr) == 1:return arr, 0mid = len(arr) // 2left, sum_left = merge_sort(arr[:mid])right, sum_right = merge_sort(arr[mid:])# Merging arraysarr, sum = merge(sum_left + sum_right, left, right)return arr, sumdef merge(sum, left, right):i = j = 0arr = []while (i < len(left) and j < len(right)):if left[i] < right[j]:arr.append(left[i])sum += left[i] * (len(right) - j)i += 1else:arr.append(right[j])j += 1while (i < len(left)):arr.append(left[i])i += 1while (j < len(right)):arr.append(right[j])j += 1return arr, sumif __name__ == '__main__':arr = [2, 3, 8, 6, 7, 4, 5]print(merge_sort(arr)[1])
Reverse order pair problem

We need to arrange the array in descending order , Every time I merge , Find a number larger on the left than on the right ,print. Empathy , Because arrays are merged in descending order every time , therefore , When a number on the left is greater than a number on the right , So it is greater than all the numbers after the number on the right .
def merge_sort(arr):# Recursively decompose the array , When there is only one element left , Stop decomposingif len(arr) == 1:return arrmid = len(arr) // 2left = merge_sort(arr[:mid])right = merge_sort(arr[mid:])# Merging arraysarr = merge(left, right)return arrdef merge(left, right):i = j = 0arr = []while (i < len(left) and j < len(right)):if left[i] > right[j]:arr.append(left[i])print('(' + str(left[i]) + ',' + str(right[j]) + ')')tmp_j = j+1while (tmp_j < len(right)):print('(' + str(left[i]) + ',' + str(right[tmp_j]) + ')')tmp_j += 1i += 1else:arr.append(right[j])j += 1while (i < len(left)):arr.append(left[i])i += 1while (j < len(right)):arr.append(right[j])j += 1return arrif __name__ == '__main__':arr = [2, 3, 8, 6, 7, 4, 5]print(merge_sort(arr))
Optimize
Detect natural ordered sub segments in the sequence , If a strictly descending sub segment is detected, the sequence is reversed to an ascending sub segment , In the best case, whether ascending or descending, the time complexity will be o(n), It has strong adaptability . This method becomes Timsort.
summary
Many people may be acm Some programming competitions will study this algorithm , In the actual work project, if not to study the underlying source code , You won't be exposed to this merging sort . In the actual interview, as long as you can say the general idea of divide and rule , I think the interviewer will let you pass .
边栏推荐
- The beginning of manjaro's journey
- [machine learning] machine learning from zero to mastery -- teach you to understand the principle of decision tree
- Patrol script
- Uncover n core 'black magic' of Presto + alluxio
- Yolov4 reading notes (with mind map)! YOLOv4: Optimal Speed and Accuracy of Object Detection
- New generation engineers teach you how to play with alluxio + ml (Part 2)
- What is ARP (address resolution protocol)? (Powercert animated videos)
- Why doesn't anyone read your hard-working blog? Do you really understand the skills of framing, typesetting and drawing?
- [opencv] opencv from introduction to mastery -- detailed explanation of input and output XML and yaml files
- Feature Engineering in simple terms – a practice guide based on openmldb (Part 1)
猜你喜欢

How to solve the problem of flash write protection in STM32?
The live registration is hot to start | the first show of Apache dolphin scheduler meetup in 2022!
![[nail scenario capability package] hospital visitor verification](/img/0e/43433ca5586c48d01708e5fa39a808.jpg)
[nail scenario capability package] hospital visitor verification

Installing mysql8 under centos8
2022 oceanbase technical essay contest officially opened | come and release your force

Compile 6relayd using the cross compiler
Online yaml to XML tool

Heavy update! Yolov4 latest paper! Interpreting yolov4 framework
Uncover n core 'black magic' of Presto + alluxio
![[nailing scenario capability package] manage the on-the-job / off-the-job situation of employees](/img/ec/c2f342a54ab69d8b834a8a1c8f8a01.jpg)
[nailing scenario capability package] manage the on-the-job / off-the-job situation of employees
随机推荐
Finger collar pin exclusive Medal
Xshell mouse configuration
Local variables and global variables in C language
Introduction to interface test, interface protocol and common interface test tools
Working principle and experimental analysis of DHCP
Installing mysql8 under centos8
How to close gracefully after using jedis
C language: array with length 0
Ensure the decentralization and availability of Oracle network
Kubernetes related knowledge - surprise interview
Install JDK, MySQL and nexus under Linux (tar package installation)
Explain memcached principle in detail
Lantern Festival, learning at the right time! Novice training camp attacks again, learning buff continues to fill up
Idea implements hot deployment
1.1-mq visual client preliminary practice
[nailing scenario capability package] enterprise and public institution intelligent access control
The SH runtime directly reported an error syntax error near unexpected token ` $'. \r‘
After 20 days' interview, I finally joined Ali (share the interview process)
04 disk space management
A simple file searcher