测试题
Merge Sort (Function Problem)
The task is to complete merge() function which is used to implement Merge Sort.
Input:
First line of the input denotes number of test cases 'T'. First line of the test case is the size of array and second line consists of array elements.
Output:
Sorted array in increasing order is displayed to the user.
Constraints:
1 <=T<= 50
1 <=N<= 1000
1 <=arr[i]<= 1000
Example:
Input:
2
5
4 1 3 9 7
10
10 9 8 7 6 5 4 3 2 1
Output:
1 3 4 7 9
1 2 3 4 5 6 7 8 9 10
C++
/*
Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function would be added by GfG's Online Judge.*/
/* The task is to complete merge() which is used
in below mergeSort() */
/* l is for left index and r is right index of the
sub-array of arr to be sorted
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
} */
// Merges two subarrays of arr[]. First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Your code here
int arr_len = r-l+1;
int arr_tmp[arr_len];
int i = 0; //equal l-l
int j = m+1-l;
for(int s = 0; s<=r-l; s++)
{
arr_tmp[s] = arr[s+l];
}
int k = l;
while(i<=m-l && j<=r-l)
{
if(arr_tmp[i]<=arr_tmp[j])
{
arr[k] = arr_tmp[i];
i++;
}
else
{
arr[k] = arr_tmp[j];
j++;
}
k++;
}
while(i<=m-l)
{
arr[k] = arr_tmp[i];
i++;
k++;
}
while(j<=r-l)
{
arr[k] = arr_tmp[j];
j++;
k++;
}
}