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]