Merge Sort using Method and Constructor in JAVA - Java2021 : Online Tutorials Hub

Java2021 : Online Tutorials Hub

JAVA | Advance Java | MySQL | Data Structure | Git | HTML | CSS | JS

Latest

Post Top Ad

Thursday, July 2, 2020

Merge Sort using Method and Constructor in JAVA

Merge Sort in Java using Method and Constructor 
-- Merge sort work in Divide and Conquer technique


public class MergeSort {
    int[]array;
    int[]tempMergeArr;
    int length;
    public static void main(String[] args) {
        int [] inputArr={48,36,13,52,19,94,21};
        MergeSort ms=new MergeSort();
        ms.sort(inputArr);
        for (int i:inputArr){
            System.out.print(i+" ");
        }
    }
    public void sort(int inputArr[]){
        this.array=inputArr;
        this.length=inputArr.length;
        this.tempMergeArr=new int[length];
        divideArray(0,length-1);
    }
    public void divideArray(int lowerIndex,int higherIndex){
        if (lowerIndex<higherIndex){
            int middle=lowerIndex+(higherIndex-lowerIndex)/2;
            //it will sort left side of an array
            divideArray(lowerIndex,middle);
            //it will show right side of an array
            divideArray(middle+1,higherIndex);
            mergeArray(lowerIndex,middle,higherIndex);
        }
    }
    public void mergeArray(int lowerIndex,int middle,int higherIndex){
        for (int i=lowerIndex;i<=higherIndex;i++){
            tempMergeArr[i]=array[i];
        }
        int i=lowerIndex;
        int j=middle+1;
        int k=lowerIndex;
        while (i<=middle && j<=higherIndex){
            if (tempMergeArr[i]<=tempMergeArr[j]){
                array[k]=tempMergeArr[i];
                i++;
            }
            else {
                array[k]=tempMergeArr[j];
                j++;
            }
            k++;
        }
        while(i<=middle){
            array[k]=tempMergeArr[i];
            k++;
            i++;
        }
    }
}
Output : 



Sorting and Searching Programs
Start with your Choice
-Important Programs for Freshers
Learn Pattern Programs 
Click to learn Array Programs
Click to Learn MySQL 
for any complaint regarding my Blog please visit contact us page and write what problem you have!

Learn with us | HTML | CSS | JS | Bootstrap | JAVA | ADV JAVA | SQL | GIT

No comments:

Pages