|
| 1 | +package Proj1; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +public class Uppgift6 { |
| 6 | + |
| 7 | + public static int[] mergeArrays(int[] a, int[] b) { |
| 8 | + |
| 9 | + try { |
| 10 | + int[] arr = new int[a.length + b.length]; // Initializing new array with the length of a+b |
| 11 | + int i = 0, j = 0, k = 0; |
| 12 | + while (i < a.length && j < b.length) { // Comparing elements with eachother and depending |
| 13 | + if (a[i] < b[j]) { // on which element that is lower than the other |
| 14 | + arr[k] = a[i]; // we put that element in the new array |
| 15 | + i++; |
| 16 | + k++; |
| 17 | + } else { |
| 18 | + arr[k] = b[j]; |
| 19 | + j++; |
| 20 | + k++; |
| 21 | + } |
| 22 | + |
| 23 | + } |
| 24 | + |
| 25 | + if (i < a.length) { // These arraycopy's take what's rest of an array and |
| 26 | + // Fills the rest of the new array the rest |
| 27 | + System.arraycopy(a, i, arr, k, (a.length - i)); |
| 28 | + } |
| 29 | + |
| 30 | + if (j < b.length) { |
| 31 | + |
| 32 | + System.arraycopy(b, j, arr, k, (b.length - j)); |
| 33 | + |
| 34 | + } |
| 35 | + return arr; |
| 36 | + |
| 37 | + } catch (Exception e) { |
| 38 | + System.out.println("Error occured"); |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + public static boolean isSorted(int[] a) { // Checking so that the array is sorted |
| 46 | + try { |
| 47 | + for (int i = a.length - 1; i > 0; i--) { |
| 48 | + if (a[i] < a[i - 1]) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + } |
| 52 | + } catch (Exception e) { |
| 53 | + |
| 54 | + } |
| 55 | + return true; |
| 56 | + } |
| 57 | + |
| 58 | + public static void main(String[] cmdln) { |
| 59 | + for (int i = 0; i < 20; i++) { |
| 60 | + int[] a = new int[(int) (Math.random() * 26) + 1]; //Creating arrays with 1-25 elements |
| 61 | + int[] b = new int[(int) (Math.random() * 26) + 1]; |
| 62 | + |
| 63 | + for (int j = 0; j < a.length; j++) { // Filling the new arrays with values between 1-100 |
| 64 | + a[j] = (int) (Math.random() * 100) + 1; |
| 65 | + } |
| 66 | + for (int j = 0; j < b.length; j++) { |
| 67 | + b[j] = (int) (Math.random() * 100) + 1; |
| 68 | + } |
| 69 | + |
| 70 | + Arrays.sort(a); // Sorting new arrays |
| 71 | + Arrays.sort(b); |
| 72 | + |
| 73 | + int[] c = mergeArrays(a, b); |
| 74 | + System.out.println(Arrays.toString(c)); |
| 75 | + System.out.println(isSorted(c)); |
| 76 | + |
| 77 | + } |
| 78 | + |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments