首页 > 后端开发 > C++ > 正文

从两个已排序的数组中打印出不常见的元素

WBOY
发布: 2023-09-12 22:09:16
转载
1435 人浏览过

从两个已排序的数组中打印出不常见的元素

给定两个已排序的数组,输出应显示它们的非公共元素

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
登录后复制

以上是从两个已排序的数组中打印出不常见的元素的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!