Write C++ program to merge two sorted array


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. #define MAX_SIZE 100 //Maximum size of the array
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. int arr1[MAX_SIZE], arr2[MAX_SIZE], mergeArray[MAX_SIZE];
  8. int size1, size2, mergeSize;
  9. int index1, index2, mergeIndex;
  10. int i;
  11.  
  12. //Reading size of the array
  13. cout<<"Enter the size of 1st array : ";
  14. cin>>size1;
  15.  
  16. //Reading elements in the array
  17. cout<<"Enter elements in 1st array : ";
  18. for(i=0; i<size1; i++)
  19. {
  20. cin>>arr1[i];
  21. }
  22.  
  23. //Reading elements in the array
  24. cout<<"\nEnter the size of 2nd array : ";
  25. cin>>size2;
  26.  
  27. //Reading elements in 2nd array
  28. cout<<"Enter elements in 2nd array : ";
  29. for(i=0; i<size2; i++)
  30. {
  31. cin>>arr2[i];
  32. }
  33.  
  34. mergeSize = size1 + size2;
  35.  
  36.  
  37. //Merging two array in ascending order
  38. index1 = 0;
  39. index2 = 0;
  40. for(mergeIndex=0; mergeIndex < mergeSize; mergeIndex++)
  41. {
  42.  
  43. //If all elements of one array is merged to final array
  44. if(index1 >= size1 || index2 >= size2)
  45. {
  46. break;
  47. }
  48. if(arr1[index1] < arr2[index2])
  49. {
  50. mergeArray[mergeIndex] = arr1[index1];
  51. index1++;
  52. }
  53. else
  54. {
  55. mergeArray[mergeIndex] = arr2[index2];
  56. index2++;
  57. }
  58. }
  59.  
  60. //Merging the remaining elements of array
  61. while(index1 < size1)
  62. {
  63. mergeArray[mergeIndex] = arr1[index1];
  64. mergeIndex++;
  65. index1++;
  66. }
  67. while(index2 < size2)
  68. {
  69. mergeArray[mergeIndex] = arr2[index2];
  70. mergeIndex++;
  71. index2++;
  72. }
  73.  
  74. //Print merged array
  75. cout<<"\nArray merged in ascending order : ";
  76. for(i=0; i<mergeSize; i++)
  77. {
  78. cout<<"\t"<< mergeArray[i];
  79. }
  80.  
  81. return 0;
  82. }

Result

C++ language techstudy.org

     





Related Topics




Popular Posts