From ee27a4462834b794ce700df8a72f658a3a490481 Mon Sep 17 00:00:00 2001 From: prasoonjain006 Date: Wed, 17 Feb 2021 12:28:14 +0530 Subject: [PATCH] add solution to ques_14.11 --- MergeSortVariation.java | 143 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 MergeSortVariation.java diff --git a/MergeSortVariation.java b/MergeSortVariation.java new file mode 100644 index 0000000..0a869c2 --- /dev/null +++ b/MergeSortVariation.java @@ -0,0 +1,143 @@ +//package practiceQuestions; + +/* +Page 667 +Problem 14.11 +(Implement iterative variation of merge sort, + merge adjacent regions at a time) + */ +import java.util.Scanner; + +/** + * @author Prasoon Jain + * + */ +public class MergeSortVariation { + + //method returns true if the number is power of two + /** + * @param number + * @return + */ + private static boolean isPowerofTwo(int number) { + if ((number & (number - 1)) == 0) + return true; + return false; + } + + //method to compare elements of adjacent regions and merge them + /** + * @param givenArray + * @param sizeofadjacentRegion + * @param leftRegionStartpoint + * @param rightRegionStartPoint + */ + private static void compareAndMergeAdjacentRegions(int givenArray[], + int sizeofadjacentRegion, int leftRegionStartpoint, + int rightRegionStartPoint) { + + int temporaryArray[] = new int[2 * sizeofadjacentRegion]; + int tempArrayIndex = 0; + int leftRegionIndex = leftRegionStartpoint; + int rightRegionIndex = rightRegionStartPoint; + int leftRegionEndPoint = leftRegionStartpoint + + sizeofadjacentRegion; + int rightRegionEndPoint=rightRegionStartPoint + + sizeofadjacentRegion; + + // comparing and merging the left and right regions elements + while(leftRegionIndex < leftRegionEndPoint + && rightRegionIndex < rightRegionEndPoint) { + + if (givenArray[leftRegionIndex] <= givenArray[rightRegionIndex]) { + temporaryArray[tempArrayIndex] = givenArray[leftRegionIndex]; + leftRegionIndex++; + } else if(givenArray[rightRegionIndex]