In: Computer Science
Please solve this problem, in c++ (algoritms) write code and explaination how to solve it!
1) N numbers are given. The first K of them are sorted in ascending order, the remaining NK are also sorted in ascending order. Sort numbers in ascending order in O (N).
Input data format N - number of numbers, K - number of numbers in the first half (sorted).
Example input
10 6
1 2 5 6 8 9 3 4 7 12
Sample Output
1 2 3 4 5 6 7 8 9 12
C++program execution starts with main() function. So define a main() function and declare required variables.
Loop body has fixed number of statements and hence loop body has constant time complexity, and we are using only one for-loop for sorting, and i varies from 0 to n-1. Hence the complexity of sorting = O(N)
Program:
#include <iostream>
using namespace std;
int main()
{
    int n, k;                           /* declare variables */
    cin>>n>>k;                          /* read n and k */
    int arr[n];                         /* declare array arr to store input data */
    int sorted[n];                      /* declare array sorted to store sorted elements */
    for(int i=0;i<n;i++){               /* read n inputs */
        cin>>arr[i];
    }
    int a=0, b=k;                       /* initialize a=0 and b=k */
    
    for(int i=0;i<n;i++){               /*for i varies from 1 to n-1 */
        if(b>=n||a<k&&arr[a]<arr[b]){   /* if b>n or (a<k and arr[a]<arr[b]) */
            sorted[i] = arr[a];         /* add element from first half to sorted */
            a++;                        /* increment a */
        }
        else{                           /* otherwise add element from last half to sorted */
            sorted[i] = arr[b];
            b++;                        /* increment b */
        }
    }
    
    for(int i=0;i<n;i++){               /* print sorted array */
        cout<<sorted[i]<<" ";
    }
    return 0;
}
Screenshot:

Output:

Please don't forget to give a Thumbs Up.