Cod sursa(job #2197152)

Utilizator catalinmatei13Stan Catalin catalinmatei13 Data 21 aprilie 2018 11:41:12
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>

using namespace std;
void Merge(int *a, int low, int high, int mid)
{
	// We have low to mid and mid+1 to high already sorted.
	int i, j, k, temp[high-low+1];
	i = low;
	k = 0;
	j = mid + 1;
 
	// Merge the two parts into temp[].
	while (i <= mid && j <= high)
	{
		if (a[i] < a[j])
		{
			temp[k] = a[i];
			k++;
			i++;
		}
		else
		{
			temp[k] = a[j];
			k++;
			j++;
		}
	}
 
	// Insert all the remaining values from i to mid into temp[].
	while (i <= mid)
	{
		temp[k] = a[i];
		k++;
		i++;
	}
 
	// Insert all the remaining values from j to high into temp[].
	while (j <= high)
	{
		temp[k] = a[j];
		k++;
		j++;
	}
 
 
	// Assign sorted data stored in temp[] to a[].
	for (i = low; i <= high; i++)
	{
		a[i] = temp[i-low];
	}
}
 
// A function to split array into two parts.
void MergeSort(int *a, int low, int high)
{
	int mid;
	if (low < high)
	{
		mid=(low+high)/2;
		// Split the data into two half.
		MergeSort(a, low, mid);
		MergeSort(a, mid+1, high);
 
		// Merge them to get sorted output.
		Merge(a, low, high, mid);
	}
}
int main (){
	int N,v[1000],i,w[1000],M,c[2000];
	ifstream f("algsort.in");
	ofstream g("algsort.out");
		
	f>>N;
	for(i=1;i<=N;i++)
		f>>v[i];
	f>>M;
	for(i=1;i<=M;i++){
		f>>w[i];
	}
	for(i=1;i<=N;i++)
		c[i]=v[i];
	for(i=1;i<=M;i++){
		c[i+N]=w[i];
	}
	int s=0;
	s=M+N;
	MergeSort(c,1,s);
	for(i=1;i<=s;i++)
		g<<c[i]<<" ";
	return 0;
}