Code From Class 2026/03/30
#include<iostream>
struct SN{
public:
long c;
SN* aN;
};
SN* push(SN* aOT, long x){
SN* aNT=new SN;
aNT->c=x;
aNT->aN=aOT;
return aNT;
}
SN* pop(SN* aOT){
if(aOT==nullptr){return nullptr;}
SN* aNT=aOT->aN;
delete aOT;
return aNT;
}
long* readArrayFromInput(long& N){
SN* aT=nullptr;
long uI;
N=0;
std::cin>>uI;
while(uI>0){
aT=push(aT,uI);
std::cin>>uI;
++N;
}
long* aX=new long[N];
for(long i=0;i<N;++i){
aX[i]=aT->c;
aT=pop(aT);
}
return aX;
}
void mergeTwoSortedArrays(long* a1, long* a2, long* aM,
long l1, long l2){
// assumes that a1 and a2 are sorted and that the
// memory is allocated for aM
long c1=0; long c2=0; long cM=0;
while( (c1<l1) || (c2<l2) ){
if(c1>=l1){
// We have already copied all of the elements
// of a1. We must copy the element of a2
aM[cM]=a2[c2];++c2;
}
else if(c2>=l2){
// We have already copied all of the elements of
// a2. We must copy the next element of a1
aM[cM]=a1[c1];++c1;
}
else if( a1[c1]<a2[c2] ){
aM[cM]=a1[c1];++c1;
}
else{
aM[cM]=a2[c2];++c2;
}
++cM;
}
}
void mSort(long* a, long n){
if(n<2){return;}
// Step 1: Split the array into two
long m=n/2;
// Step 2: Sort the left
mSort(a,m);
// Step 3: Sort the right
mSort(a+m,n-m);
// Step 4: Merge the two sorted arrays
long* aMerged=new long[n];
mergeTwoSortedArrays(a,a+m,aMerged,m,n-m);
for(long i=0;i<n;++i){
a[i]=aMerged[i];
}
delete[] aMerged;
}
int main(){
long n;
long* a=readArrayFromInput(n);
mSort(a,n);
for(long i=0;i<n;++i){
std::cout<<a[i]<<" ";
}
std::cout<<"\n";
if(n>1){
long smallestDistance=a[1]-a[0];
// In each iteration of the loop we will
// calculate the distance a[i]-a[i-1]
// We will check whether this is smaller than the
// previously found smallest distance.
long minimizingI=1;
long i=2;
while(i<n){
if( a[i]-a[i-1]<smallestDistance ){
smallestDistance=a[i]-a[i-1];
minimizingI=i;
}
++i;
}
std::cout<<"The smallest distance is "<<smallestDistance;
std::cout<<". The closest elements are ";
std::cout<<a[minimizingI-1];
std::cout<<" and ";
std::cout<<a[minimizingI]<<".\n";
}
else{
std::cout<<"There are not enough elements in the array.\n";
}
delete[] a;
return 0;
}