Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class Main{
- public static void main(String[] args){
- Scanner scan = new Scanner(System.in);
- int[] first = new int[10000];
- int[] second = new int[10000];
- int cfirst = 0;
- int csecond = 0;
- //gets values for first array
- System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");
- for (int i = 0 ; i < first.length; i++ ) {
- first[i] = scan.nextInt();
- cfirst++;
- if(first[i] < 0){
- first [i] = 0;
- break;
- }
- }
- //gets values for second array
- System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");
- for (int m = 0 ; m < second.length; m++ ) {
- second[m] = scan.nextInt();
- csecond++;
- if(second[m] < 0){
- second [m] = 0;
- break;
- }
- }
- //prints first array
- System.out.println("First Array:");
- for(int j=0; j<cfirst-1 ; j++){
- System.out.print(first[j] + " ");
- }
- //prints second array
- System.out.println(" \nSecond Array:");
- for(int k=0; k<csecond-1; k++){
- System.out.print(second[k] + " ");
- }
- //code to check is first && second are ordered
- boolean firstorder = true;
- for (int o = 1; o < cfirst-1; o++) {
- if (first[o] < first[o - 1]){
- firstorder = false;
- }
- }
- boolean secondorder = true;
- for (int f = 1; f < csecond-1; f++) {
- if (second[f] < second[f - 1]){
- secondorder = false;
- }
- }
- int[] merged = new int[cfirst-1 + csecond-1];
- if(secondorder && firstorder){
- int q = 0, w = 0, e = 0;
- while (q < cfirst-1 && w < csecond-1) {
- merged[e] = Math.min(first[q],second[w]);
- if(first[q] >= second[w]) w++;
- else q++;
- e++;
- }
- while(w<csecond-1 || q<cfirst-1){
- if (w >= csecond) merged[e] = first[q];
- else merged[e] = second[w];
- q++;
- w++;
- e++;
- }
- }
- //returns the merged array || returns error
- if(!firstorder || !secondorder){
- System.out.println("\nERROR: Array not in correct order");
- }else if(firstorder && secondorder){
- System.out.println("\nMerged Array");
- for(int l=0; l<(cfirst-1 + csecond-1); l++){
- System.out.print(merged[l] + " ");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement