Question #38344

Write a program to input integer data in two arrays. Sort one of the arrays in ascending order and the other in descending order. Then merge them into a third array so that the ata in the third array is in ascending order. The program should then display the data from all the three arrays.

Expert's answer

//Answer on Question #38344, Programming, C++


#include <cstdlib>
#include <iostream>
using namespace std;
void sort(int A[], int size, int type);
//main function
int main(int argc, char *argv[])
{
    int n1, n2; //variable for n1 n2
    cout << "Enter total values for first array: ";
    cin >> n1; //read n1
    cout << "Enter total values for second array: ";
    cin >> n2; //read n2
    //variable for arrays
    int firstArray[n1];
    int secondArray[n2];
    int n3 = n1 + n2; //calculate total number of values
    int mergeArray[n3];
    //enter values for first array
    cout << "Enter values for first array:\n";
    for(int i = 0; i < n1; i++) {
        cout << "Enter value "<< i <<": ";
        cin >> firstArray[i];
    }
    //enter values for second array
    cout << "Enter values for second array:\n";
    for(int i = 0; i < n2; i++) {
        cout << "Enter value "<< i <<": ";
        cin >> secondArray[i];
    }
    //sort first array
    sort(firstArray, n1, 1);
    //sort second array
    sort(secondArray, n2, 2);
    //merge arrays
    for(int i = 0; i < n1; i++) {
        mergeArray[i] = firstArray[i];
    }
    for(int i = 0; i < n2; i++) {
        mergeArray[n1 + i] = secondArray[i];
    }
}
void sort(int A[], int size, int type) {
    for(int i = 0; i < size - 1; i++) {
        for(int j = 0; j < size - i - 1; j++) {
            if(type == 1) {
                if(A[j] > A[j + 1]) {
                    int temp = A[j];
                    A[j] = A[j + 1];
                    A[j + 1] = temp;
                }
            }
            if(type == 2) {
                if(A[j] < A[j + 1]) {
                    int temp = A[j];
                    A[j] = A[j + 1];
                    A[j + 1] = temp;
                }
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS