From 24c4798267c15071c3e1ab95fdfd095b84607d58 Mon Sep 17 00:00:00 2001 From: Bogdan Popov Date: Sun, 30 Oct 2016 21:02:29 +0300 Subject: [PATCH] solution of sorting two arrays added --- src/TechInterview/MergeArrays.java | 74 ++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/TechInterview/MergeArrays.java diff --git a/src/TechInterview/MergeArrays.java b/src/TechInterview/MergeArrays.java new file mode 100644 index 0000000..fa3378b --- /dev/null +++ b/src/TechInterview/MergeArrays.java @@ -0,0 +1,74 @@ +package TechInterview; + +import java.util.Arrays; +import java.util.Random; + +/** + * Solution to the problem #9.1 about merging two sorted arrays + * of chapter 'Sorting and Searching' from book 'Cracking the Coding Interview'. + */ + +public class MergeArrays { + + private static int SIZE_A = 50; + private static int SIZE_B = 15; + + public static void main(String[] args) { + + + int[] arrayA = new int[SIZE_A]; + int[] arrayB = new int[SIZE_B]; + + + Random random = new Random(); + for (int i = 0; i < (SIZE_A - SIZE_B); i++) { + int q = random.nextInt(100); + arrayA[i] = q; + } + + + for (int i = 0; i < SIZE_B; i++) { + int q = random.nextInt(100); + + arrayB[i] = q; + } + + Arrays.sort(arrayA, 0, SIZE_A - SIZE_B); + Arrays.sort(arrayB, 0, SIZE_B); + + System.out.println("Array A before merge"); + for (int i : arrayA) + System.out.print(i + " "); + System.out.println("\nArray B before merge"); + for (int i : arrayB) + System.out.print(i + " "); + + System.out.println("\n\nMerging..."); + mergeArrays(arrayA, arrayB); + + } + + private static void mergeArrays(int[] arrayA, int[] arrayB) { + + int i = SIZE_A - SIZE_B - 1; + int j = SIZE_B - 1; + while (i >= 0 && j >= 0) { + if (arrayA[i] > arrayB[j]) { + arrayA[i + j + 1] = arrayA[i]; + i--; + } else { + arrayA[i + j + 1] = arrayB[j]; + j--; + } + } + + while (j >= 0) { + arrayA[i + j + 1] = arrayB[j]; + j--; + } + + System.out.println("\nArray A after merge:"); + for (int k : arrayA) + System.out.print(k + " "); + } +}