Friday 1 September 2017

Java Code to Merge Two Arrays

Problem:

Merge two arrays of integers, both with their elements in ascending order, into a single ordered array.

Solution:

package array.programs;

import java.util.Scanner;

public class MergeTwoArrays {

int[] firstArray;
int[] secondArray;
int[] resultArray;
int firstArrayLimit;
int secondArrayLimit;

public static void main(String[] args) {
MergeTwoArrays mergeTwoArrays = new MergeTwoArrays();
mergeTwoArrays.initializeTheArray();
mergeTwoArrays.mergaTwoArrays();
mergeTwoArrays.printTheArray();
}

public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first array elements limit");
firstArrayLimit = scanner.nextInt();
firstArray = new int[firstArrayLimit];
for (int i = 0; i < firstArray.length; i++) {
System.out.println("enter the element");
firstArray[i] = scanner.nextInt();
}

System.out.println("enter the second array elements limit");
secondArrayLimit = scanner.nextInt();
secondArray = new int[secondArrayLimit];
for (int i = 0; i < secondArray.length; i++) {
System.out.println("enter the number");
secondArray[i] = scanner.nextInt();
}

resultArray = new int[firstArrayLimit + secondArrayLimit];

scanner.close();

}

public void mergaTwoArrays(){
int i = 0;
int j = 0;
int k = 0;
while (i < firstArrayLimit && j < secondArrayLimit) {
if(firstArray[i] < secondArray[j]){
resultArray[k++] = firstArray[i++];
}
else{
resultArray[k++] = secondArray[j++];
}

}

while(i < firstArrayLimit){
resultArray[k++] = firstArray[i++];
}

while(j < secondArrayLimit){
resultArray[k++] = secondArray[j++];
}
}

public void printTheArray(){
for (int i = 0; i < resultArray.length; i++) {
System.out.print( resultArray[i] + " ");
}
}

}


Output:

enter the first array elements limit
4
enter the element
15
enter the element
18
enter the element
42
enter the element
51
enter the second array elements limit
8
enter the number
8
enter the number
11
enter the number
16
enter the number
17
enter the number
44
enter the number
58
enter the number
71
enter the number
74
8 11 15 16 17 18 42 44 51 58 71 74 

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...