😸
C++で2つの配列をmergeする関数
c++で、二つの配列をmergeする関数を書いた。
#include <iostream>
using namespace std;
void merge(int left[], int right[], int left_size, int right_size){
int sorted[left_size + right_size];
int sorted_index = 0;
int left_index = 0;
int right_index = 0;
while(left_index < left_size && right_index < right_size){
if(left[left_index] <= right[right_index]){
sorted[sorted_index] = left[left_index];
sorted_index++;
left_index++;
}else{
sorted[sorted_index] = right[right_index];
sorted_index++;
right_index++;
}
}
while(right_index < right_size){
sorted[sorted_index] = right[right_index];
sorted_index++;
right_index++;
}
while(left_index < left_size){
sorted[sorted_index] = left[left_index];
sorted_index++;
left_index++;
}
for (int i = 0; i < sorted_index;i++){
cout << sorted[i] << endl;
}
}
int main() {
int left[] = {1, 4, 5, 7};
int right[] = {2, 3, 8};
merge(left, right, 4, 3);
return 0;
}
出力
1
2
3
4
5
7
8
Discussion