
Hello,
I am trying to implement a merge sort algorithm that sorts an array of Strings. I have seen numerous examples of merge-sorting integers but i can not understand how to this with String. Note: I have a separate class for merge sort in which i pass my list and the size of the list. i then copy my list in the array. the method call inside the main looks like this: merge.Sort(list, list.size()) ;.
Any help would be appreciated. Thank you

public class MergeTestStringArray {
public static void main(String[] args) {
String[] array = { "John", "Anthony", "Angelina",
"George", "Victor", "Joe", "Jackson" };
String[] sortedArray = mergeSort(array);
for (int i = 0; i < sortedArray.length; i++) {
System.out.println(sortedArray[i] + " ");
}
}
public static String[] mergeSort(String[] list) {
String [] sorted = new String[list.length];
if (list.length == 1) {
sorted = list;
} else {
int mid = list.length/2;
String[] left = null;
String[] right = null;
if ((list.length % 2) == 0) {
left = new String[list.length/2];
right = new String[list.length/2];
} else {
left = new String[list.length/2];
right = new String[(list.length/2)+1];
}
int x=0;
int y=0;
for ( ; x < mid; x++) {
left[x] = list[x];
}
for ( ; x < list.length; x++) {
right[y++] = list[x];
}
left = mergeSort(left);
right = mergeSort(right);
sorted = mergeArray(left,right);
}
return sorted;
}
private static String[] mergeArray(String[] left, String[] right) {
String[] merged = new String[left.length+right.length];
int lIndex = 0;
int rIndex = 0;
int mIndex = 0;
int comp = 0;
while (lIndex < left.length || rIndex < right.length) {
if (lIndex == left.length) {
merged[mIndex++] = right[rIndex++];
} else if (rIndex == right.length) {
merged[mIndex++] = left[lIndex++];
} else {
comp = left[lIndex].compareTo(right[rIndex]);
if (comp > 0) {
merged[mIndex++] = right[rIndex++];
} else if (comp < 0) {
merged[mIndex++] = left[lIndex++];
} else {
merged[mIndex++] = left[lIndex++];
}
}
}
return merged;
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.