gpt4 book ai didi

java - 字符串归并排序实现

转载 作者:行者123 更新时间:2023-11-29 07:15:08 27 4
gpt4 key购买 nike

我一直在尝试在正在开发的程序中实现各种类型的排序。到目前为止,我已经设法对整数进行排序。为了使此(合并)代码对 String 数组而不是 int 数组进行排序,必须进行哪些更改?时间复杂度会变化吗?如果是这样,是好是坏?

编辑 1:尝试使用 compareTo。有些事情似乎不对。返回错误,例如无法从字符串转换为 int,反之亦然。固定

编辑 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++;
}
}
}

}

最佳答案

这取决于您想要对字符串进行排序的方式,但是StringcompareTo 方法|将帮助您实现这种排序:

Returns: the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

关于java - 字符串归并排序实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10232441/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com