Computer >> Máy Tính >  >> Lập trình >> C ++

Hợp nhất hai mảng chưa được sắp xếp theo thứ tự đã sắp xếp trong C ++.

Tuyên bố vấn đề

Viết một hàm nhận hai mảng chưa được sắp xếp và hợp nhất chúng thành một mảng mới theo thứ tự đã sắp xếp.

arr1[] = {10, 5, 7, 2}
arr2[] = {4, 17, 9, 3}
result[] = {2, 3, 4, 5, 7, 9, 10, 17}

Thuật toán

1. Merge two unsorted array into new array
2. Sort newly create array

Ví dụ

#include <iostream>
#include <algorithm>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
void mergeAndSort(int *arr1, int n1, int *arr2, int n2, int *result){
   merge(arr1, arr1 + n1, arr2, arr2 + n2, result);
   sort(result, result + n1 + n2);
}
void displayArray(int *arr, int n){
   for (int i = 0; i < n; ++i) {
      cout << arr[i] << " ";
   }
   cout << endl;
}
int main(){
   int arr1[] = {10, 5, 7, 2};
   int arr2[] = {4, 17, 9, 3};
   int result[SIZE(arr1) + SIZE(arr2)];
   cout << "First array: " << endl;
   displayArray(arr1, SIZE(arr1));
   cout << "Second array: " << endl;
   displayArray(arr1, SIZE(arr2));
   mergeAndSort(arr1, SIZE(arr1), arr2, SIZE(arr2), result);
   cout << "Merged and sorted array: " << endl;
   displayArray(result, SIZE(arr1) + SIZE(arr2));
   return 0;
}

Đầu ra

Khi bạn biên dịch và thực thi chương trình trên. Nó tạo ra kết quả sau -

First array:
10 5 7 2
Second array:
10 5 7 2
Merged and sorted array:
2 3 4 5 7 9 10 17