当前位置:网站首页>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 .
边栏推荐
- OSI notes sorting
- IPtables
- 炒股票用指南针安全还是用证券软件安全?哪里可以开户怎么开
- Finger collar pin exclusive Medal
- [nailing scenario capability package] ranking of enterprise employees' points
- Tencent music knowledge map search practice
- What is a server? (Powercert animated videos)
- MySQL is slow to add indexes_ Why is your SQL so slow? Why is your MySQL index invalid?
- Working principle and experimental analysis of DHCP
- Great changes in the interaction between people and the digital world
猜你喜欢

Molecular dynamics - basic characteristics of molecular force field

Yolov4 improved version comes out! Yolov4 extended edition! Yolov4 launched scaled-yolov4: scaling cross stage partial network

Working principle and experimental analysis of DHCP

js (1)
Cloud development practice of the small program for brushing questions in the postgraduate entrance examination - page design and production (home page of the question bank, ranking page, my)
R language momentum and Markowitz portfolio model implementation

Explain memcached principle in detail
![[nailing scenario capability package] company / Park Digital canteen](/img/72/eb3df1945532c4e7813e15f9cf90c5.jpg)
[nailing scenario capability package] company / Park Digital canteen

Sqlmap for interface security testing
Tencent music knowledge map search practice
随机推荐
How to buy the millions of medical insurance for children? How much is it a year? Which product is the best?
What is API
Chrome plugin installation
What is ARP (address resolution protocol)? (Powercert animated videos)
Sqlmap for interface security testing
Multi database and multi table backup and restore of MySQL under Linux
Beginner to embedded development
[data recovery in North Asia] a data recovery case in which the upper virtual machine data is lost due to the hard disk failure and disconnection of raid6 disk array
Section 13: simplify your code with Lombok
Cvpr2019 | the latest cvpr2019 papers are the first to read!
Get the root directory of the package at compile time from buildreoot
laf. JS - open source cloud development framework (readme.md)
同花顺app是正规的吗?到底安不安全
Openocd adds third-party device support: ht32f52352 Cortex-M0+
Cvpr2020 | the latest cvpr2020 papers are the first to see, with all download links attached!
VFS appears when mounting a file system from an SD card: cannot open root device "mmcblk1p2“
How to solve the problem of flash write protection in STM32?
[phase 23] phased summary of spring recruitment practice (Alibaba cloud has OC)
What is a server? (Powercert animated videos)
Yunzhisheng atlas supercomputing platform: computing acceleration practice based on fluid + alluxio (Part I)