I wanted to write a program to take two arrays as input and convert the first array such that the difference of maximum value and minimum value from the first array gives the smallest possible number.
I tried to write a code to find a smaller number most closest to the maximum from the array in C , but the function for finding the minimum works on Codelite, but not on other compilers; Is there any fix to solve this, either to the code or the compiler?
Here is the code I tried:
#include <iostream>
using namespace std;
void swap(int A[], int B[], int n)
{
int x, y, temp;
for(x=0;x<n; x)
{
for(y=0;y<n; y)
{
if(A[x]>B[y])
{
temp = A[x];
A[x] = B[y];
B[y] = temp;
}
}
}
}
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i )
{
for (j = i; j < n; j )
{
if (A[i] > A[j 1])
{
temp = A[i];
A[i] = A[j 1];
A[j 1] = temp;
}
}
}
}
int maxfind(int A[], int n)
{
int z, a;
a = A[0];
for(z=0;z<n; z)
{
if(a<A[z])
{
a = A[z];
}
}
cout << "Max value in A is" << a << endl;
return a;
}
int minfind(int A[], int n, int amax, int amin)
{
int z, maxi;
maxi = amax;
for(z=0;z<n; z)
{
if(maxi >= A[z])
{
amin = A[z];
}
else
{
maxi = maxi-1;
}
}
cout << "Mix value in A is" << amin << endl;
return amin;
}
int main() {
int z, t;
cout << "Enter number of test cases: ";
cin >> t;
int n, i, j, amax, amin;
for(z=0;z<t; z)
{
cout << "Enter size of array" << endl;
cin >> n;
int A[n], B[n];
cout << "Enter Array A values:" << endl;
for(i=0;i<n; i)
{
cin >> A[i];
}
cout << "Enter Array B values:" << endl;
for(j=0;j<n; j)
{
cin >> B[j];
}
swap(A, B, n);
sortas(A, n);
cout << "Swapped and sorted array is: " << endl;
for(i=0;i<n; i)
{
cout << A[i] << "\t" << B[i] << endl;
}
amax = 0;
amin = 0;
amax = maxfind(A, n);
amin = minfind(A, n, amax, amin);
}
return 0;
}
Here is the output to that code:
1 1 1 3 4 2
Max value in A is 1 Min value in A is 1
1 2 2 -1882830412 4 3 6 3
Max value in A is 2 Min value in A is -1882830412
CodePudding user response:
The problem is with your bubble sort:
void sortas(int A[], int n)
{
int i, j, temp;
for (i = 0; i < n; i )
{
for (j = i; j < n; j ) // why not start at i 1 ??
{
if (A[i] > A[j 1]) // j 1 is out of bounds when j == n - 1
{
temp = A[i];
A[i] = A[j 1]; // <-- Some random value is written to A.
A[j 1] = temp; // <-- Overwriting some variable on the stack
// of main() (possibly B ?)
}
}
}
}
A correct bubble sort (this is not the pedantic bubble sort), this is probably the most used.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; i)
{
for (int j = i 1; j < n; j)
{
if (A[i] > A[j])
std::swap(A[i], A[j]);
}
}
}
The actual bubble sort algorithn (the "pedantic" bubble sort), swaps only occur on neighboring values.
void sortas(int A[], int n)
{
for (int i = 0; i < n - 1; i)
{
for (int j = 0; j < (n - i) - 1; j)
{
if (A[j] > A[j 1])
std::swap(A[j], A[j 1]);
}
}
}
Use one or the other, for integers, the performance is identical.