Write C# program to merge two sorted array


Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.


techstudy.org

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

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

Result

C# language techstudy

     





Related Topics




Popular Posts