I have been trying to implement various types of sort in a program am working on. So far i've managed to sort integers.What changes have to be made in order to make this (merge) code sort a String array instead of an int one? Will the time complexity vary? if so, for better or for worse?
EDIT 1: tried to use the compareTo. something does not seem right. Errors are returned e.g Cannot convert from string to int and vice versa. FIXED
EDIT 2: im getting NullPointerException at line if (array[low].compareTo(array[high]) >= 0) . Suggestions are always welcome.
This is the error:
null null null null null
Exception in thread "main" java.lang.NullPointerException
at Merge.mergeSort_srt(Merge.java:28)
at Merge.Sort(Merge.java:15)
at Sort.main(Sort.java:73)
import java.io.File;
public class Merge
{
public void Sort (LinkedList listIn, int size) throws Exception
{
String[] mergeArray = new String[size] ;
String textContent = null ;
File outputFile ;
for(int i = 0; i < mergeArray.length; i++)
System.out.print( mergeArray[i]+" ");
System.out.println();
mergeSort_srt(mergeArray,0, mergeArray.length-1);
System.out.print("Values after the sort:\n");
for(int i = 0; i <mergeArray.length; i++)
System.out.print(mergeArray[i]+" ");
System.out.println();
System.out.println("PAUSE");
}
public static void mergeSort_srt(String array[],int lo, int n)
{
int low = lo;
int high = n;
if (array[low].compareToIgnoreCase(array[high]) >= 0)
{
return;
}
int middle = ((n+1)/ 2);
mergeSort_srt(array, low, middle);
mergeSort_srt(array, middle + 1, high);
int end_low = middle;
int start_high = middle + 1;
while ((array[low].compareToIgnoreCase(array[end_low]) <= 0) && (array[start_high].compareToIgnoreCase(array[high]) <= 0))
{
if(array[low].compareToIgnoreCase(array[start_high]) < 0)
{
low++;
}
else
{
String Temp = array[start_high];
for (int k = start_high- 1; k >= low; k--)
{
array[k+1] = array[k];
}
array[low] = Temp;
low++;
end_low++;
start_high++;
}
}
}
}