C++ Merge sort

Sorting Principles and Ideas

The operation of merging two or more ordered sequences (or ordered lists) into one still ordered sequence (or ordered list) is called a merge operation. Such a method is often used to merge multiple ordered data files into an ordered data file. If two ordered tables are merged into one ordered table, it is called a two-way merge. Similarly, there are three-way merges, four-way merges, and so on. Two-way merge is relatively simple, so we only discuss two-way merge. For example, there are two ordered lists: (7,10,13,15)and (4,8,19,20), the ordered list obtained after merging is: (4,7,8,10,13,15,19,20).

The merging process is: compare A[i]the A[j]size of the sum, if so , copy A[i]≤A[j]the elements in the first ordered list to , and add the sums separately , even if they respectively refer to the next unit, otherwise copy the elements in the second ordered list Copy the elements of , and add the sums respectively ; this loop continues until one of the ordered lists is taken out, and then copy the remaining elements in the other ordered list to the units from subscript to subscript .A[i]R[k]ik1A[j]R[k]jk1Rkt

program implementation

define input not interpreted

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    
    
	int n,m,a[1005]={
    
    0},b[1005]={
    
    0},c[2015]={
    
    0},p=1,q=1,t=1; //p=a[];q=b[];t=c[]
	cin>>n>>m;
	for(int i=1;i<=n;i++){
    
    
		cin>>a[i];
	}
	for(int i=1;i<=m;i++){
    
    
		cin>>b[i];
	}
	
	for(int i=1;i<=(n+m);i++){
    
    
		cout<<c[i]<<" ";
	}
    return 0;
}

Then, according to the sorting idea, it is not difficult for us to write the following code:

while(p<=n&&q<=m){
    
    
	if(a[p]<b[q]){
    
    
		c[t]=a[p];
		p++;t++;
	}else{
    
    
		c[t]=b[q];
		q++;t++;
	}
}

However, these numbers will miss the following numbers, so we add a string of codes to fill in the missing numbers

if(p<=n){
    
    
	for(int i=p;i<=n;i++){
    
    
		c[t]=a[i];t++;
	}
}
if(q<=m){
    
    
	for(int i=q;i<=m;i++){
    
    
		c[t]=b[i];t++;
	}
}

The complete code is as follows:

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    
    
	int n,m,a[1005]={
    
    0},b[1005]={
    
    0},c[2015]={
    
    0},p=1,q=1,t=1; //p=a[];q=b[];t=c[]
	cin>>n>>m;
	for(int i=1;i<=n;i++){
    
    
		cin>>a[i];
	}
	for(int i=1;i<=m;i++){
    
    
		cin>>b[i];
	}
	while(p<=n&&q<=m){
    
    
		if(a[p]<b[q]){
    
    
			c[t]=a[p];
			p++;t++;
		}else{
    
    
			c[t]=b[q];
			q++;t++;
		}
	}
	if(p<=n){
    
    
		for(int i=p;i<=n;i++){
    
    
			c[t]=a[i];t++;
		}
	}
	if(q<=m){
    
    
		for(int i=q;i<=m;i++){
    
    
			c[t]=b[i];t++;
		}
	}
	for(int i=1;i<=(n+m);i++){
    
    
		cout<<c[i]<<" ";
	}
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45122104/article/details/126921155