MergeSort

mail@pastecode.io avatar
unknown
java
6 months ago
1.4 kB
1
Indexable
Never
public class MergeSort {
    public static void Divide(String arr[],int si,int ei){
        if(si>=ei){
            return;
        }
        int mid = si + (ei-si)/2;
        Divide(arr, si, mid);
        Divide(arr, mid+1, ei);
        conquer(arr, si, mid, ei);
    }
    public static void conquer(String arr[],int si,int mid,int ei){
        String temp[] = new String[ei-si+1];
        int i = si;
        int j= mid+1;
        int k = 0;
        while(i<=mid && j<=ei){
            if(isAlphabeticallySmaller(arr[i], arr[j])){
                temp[k++] = arr[i++];
            }else{
                temp[k++] = arr[j++];
            }
        }
        while (i<=mid) {
            temp[k++] = arr[i++];
        }
        while(j<=ei){
            temp[k++] = arr[j++];
        }
        for(k=0, i=si; k<temp.length; k++,i++){
            arr[i] = temp[k];
        }
    }
    public static boolean isAlphabeticallySmaller(String arr1,String arr2){
        if(arr1.compareTo(arr2)<0){
            return true;
        }
        return false;
    }
    public static void printString(String str[]){
        for(int i=0; i<str.length; i++){
            System.out.print(str[i]+" ");
        }
    }
    public static void main(String[] args) {
        String str[] = {"sun","earth","mars","mercury"};
        Divide(str, 0, str.length-1);
        printString(str);
    }   
}
Leave a Comment