ソートされた 2 つの配列から一般的ではない要素を出力する

WBOY
リリース: 2023-09-12 22:09:16
転載
1435 人が閲覧しました

ソートされた 2 つの配列から一般的ではない要素を出力する

2 つの並べ替えられた配列がある場合、出力にはそれらの非共通要素が表示されるはずです。

Given : array1[]= {1, 4, 6, 9, 12}
   array2[]= {2, 4, 7, 8, 9, 10}
Output : 1 2 6 7 8 10 12
ログイン後にコピー

アルゴリズム

START
Step 1 -> declare two arrays array1 and array2 with elements as int and variables n1, n2, i to 0 and j to 0
Step 2 -> calculate number of elements in array1 sizeof(array1)/sizeof(array1[0])
Step 3-> calculate number of elements in array2 sizeof(array2)/sizeof(array2[0])
Step 4 -> Loop While till i<n1 and j<n2
   IF array1[i]<array2[j]
      Print array1[i++]
   End IF
      ELSE If array1[i] > array2[j]
         Print array2[j++ ]
      End ELSE IF
   ELSE
      i++ and j++
   End ELSE
Step 5 -> End Loop While
Step 6 -> loop While i < n1 && array1[i]!=array2[j]
   Print array1[i++]
Step 7 -> End Loop While
Step 8 -> loop While j < n2 && array2[j]!=array1[i]
   Print array2[j++]
Step 9 -> End Loop While
STOP
ログイン後にコピー

Example

的中文翻訳:

#include <stdio.h>
int main(int argc, char const *argv[]) {
   int array1[]= {1, 4, 6, 9, 12};
   int array2[]= {2, 4, 7, 8, 9, 10};
   int n1, n2, i=0, j=0;
   n1 = sizeof(array1)/sizeof(array1[0]); //Calculating number of elements in array1
   n2 = sizeof(array2)/sizeof(array2[0]); //Calculating number of elements in array2
   while(i < n1 && j < n2) {
      if(array1[i] <array2[j]) //checking whether the element of array1 is smaller than array2
         printf("%d</p><p>", array1[i++]);
      else if (array1[i] > array2[j]) //checking whether the element of array2 is smaller than array1
         printf("%d</p><p>", array2[j++]);
      else { //if they are equal increment both i and j      
         i++;
         j++;
      }
   }
   while(i < n1 && array1[i]!=array2[j]) //print remaining array1
      printf("%d</p><p>", array1[i++]);
   while(j < n2 && array2[j]!=array1[i]) //print remaining array1
      printf("%d</p><p>", array2[j++]);
   return 0;
}
ログイン後にコピー

出力

上記のプログラムを実行すると、次の出力が生成されます

1
2
6
7
8
10
12
ログイン後にコピー

以上がソートされた 2 つの配列から一般的ではない要素を出力するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!