0% found this document useful (0 votes)
12 views2 pages

MergeSort of String

The document contains a Java class that implements the merge sort algorithm for sorting an array of strings alphabetically. It includes methods for merging two sorted arrays and checking if one string is alphabetically smaller than another. The main method demonstrates the sorting of a predefined array of planet names.

Uploaded by

rahulsuthrapu616
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

MergeSort of String

The document contains a Java class that implements the merge sort algorithm for sorting an array of strings alphabetically. It includes methods for merging two sorted arrays and checking if one string is alphabetically smaller than another. The main method demonstrates the sorting of a predefined array of planet names.

Uploaded by

rahulsuthrapu616
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

public class D_A_CQSol {

public static String[] mergeSort(String []arr,int lo, int hi){


if(lo==hi){
String [] A={arr[lo]};
return A;
}
int mid=lo+(hi-lo)/2;
String [] arr1=mergeSort(arr,lo,mid);
String [] arr2=mergeSort(arr,mid+1,hi);

String [] arr3=merge(arr1,arr2);
return arr3;
}
static String [] merge(String [] arr1, String [] arr2){
int m=arr1.length;
int n=arr2.length;
String [] arr3=new String [m+n];
int idx=0;
int i=0 , j=0;
while ( i<m && j<n ){
if(isAlphabeticallySmaller(arr1[i], arr2[j])){
arr3[idx]=arr1[i];
i++;
}
else{
arr3[idx]=arr2[j];
j++;
}
idx++;
}
while( i< m){
arr3[idx]=arr1[i];
i++; idx++;
}
while( j< n){
arr3[idx]=arr2[j];
j++; idx++;
}
return arr3;

static boolean isAlphabeticallySmaller(String str1, String str2){


if(str1.compareTo(str2)<0){
return true;
}
return false;
}

public static void main(String[] args) {


String[] a={"sun","earth","mars","mercury","pluto","satrun"};
String [] arr= mergeSort(a, 0, 5);
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}

You might also like