当前位置:网站首页>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 user name and password will be automatically filled in when adding a form
- 1.0-mq getting started and using
- Insert and update each database
- This is a simple and cool way to make large screen chart linkage. Smartbi will teach you
- Basic knowledge of software engineering required for soft test
- Why doesn't anyone read your hard-working blog? Do you really understand the skills of framing, typesetting and drawing?
- Desktop network error display red ×, Component failed to start
- Feature Engineering in simple terms – a practice guide based on openmldb (Part 1)
- [distributed system design profile (1)] raft
- 股市小白通过网上进行股票开户安全吗?
猜你喜欢

1.0-mq getting started and using

C language soul torture: do you know the difference between the two?

Xshell mouse configuration

Working principle and experimental analysis of DHCP

Sqlmap for interface security testing

A simple file searcher

OLED driven learning based on ssd1306 (II): addressing mode of ssd1306
![[nailing - scenario capability package] nailer card](/img/ec/c2f342a54ab69d8b834a8a1c8f8a01.jpg)
[nailing - scenario capability package] nailer card
Interview shock: talk about thread life cycle and transformation process?
Great changes in the interaction between people and the digital world
随机推荐
Xshell mouse configuration
1.0-mq getting started and using
HMS core actively explores the function based on hardware ear return, helping to reduce the overall singing delay rate of the singing bar by 60%
The correct way to clear the cache of the computer. The computer will not get stuck immediately after changing. practical
Nine built-in objects of JSP and four scopes of Servlet
[nailing - scenario capability package] nailer card
[nailing scenario capability package] ranking of enterprise employees' points
IPv4 and IPv6 (powercert animated videos)
Soft test intermediate simple notes
Decryption of APP parameters of a cross-border export e-commerce - dunhuang.com
very good
Interviewer: why does TCP shake hands three times and break up four times? Most people can't answer!
Code program related problems troubleshooting directory
The beginning of manjaro's journey
Is Galaxy Securities reliable? Is it safe to open a securities account?
Rounding related calculation
Live broadcast preview | front line experts invite you to talk: the value of data science enabling multiple application scenarios
How to play one to many in JPA?
laf. JS - open source cloud development framework (readme.md)
Get the root directory of the package at compile time from buildreoot