我一直在尝试在正在开发的程序中实现各种类型的排序。到目前为止,我已经设法对整数进行排序。为了使这个(合并)代码对 String 数组而不是 int 数组进行排序,必须进行哪些更改?时间复杂度会变化吗?如果是这样,是好是坏?
编辑 1:尝试使用 compareTo。似乎有些不对劲。返回错误,例如无法从字符串转换为整数,反之亦然。固定的
编辑 2:我在 if (array[low].compareTo(array[high]) >= 0) 行得到 NullPointerException。建议总是受欢迎的。
这是错误:
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++;
}
}
}
}