[英]Java Insertion Sorting with ArrayLists of Strings
我有一个关于排序的任务,要求我通过将以相同字母开头的字母放在组/区域中并按字母顺序对该组进行排序来对随机单词列表进行排序。 我的代码对单词进行了排序,但我的问题是某些单词已经改变。 例如,而不是将 output 作为
我会有一个 output :
正如你所看到的,一些单词已经改变,在某些情况下,大写字母的单词变成了小写字母,比如“cat”,我似乎找不到我的错误在哪里。
这是我的排序代码; 我的驱动程序 class 只接受随机单词列表:
import java.util.ArrayList;
import java.util.Collections;
public class ZoneSort
{
ArrayList[] arrayOfZones;
ArrayList<String> words;
public ZoneSort(ArrayList<String> words)
{
arrayOfZones = new ArrayList [ 26 ];
for(int index = 0; index < 26;index++)
arrayOfZones [ index ] = new ArrayList();
this.words = words;
putWordsIntoZones();
}
private void putWordsIntoZones()
{
for(String word: words)
{
int index = Character.toLowerCase(word.charAt(0)) - 97;
ArrayList<String> zoneAtIndex = arrayOfZones[index];
zoneAtIndex.add(word);
}
}
public void sortTheArrayOfZones()
{
for(ArrayList<String> zone : arrayOfZones )
{
sortZone(zone);
}
}
private void sortZone(ArrayList<String> zone)
{
for(int i = 1; i < zone.size(); i++)
{
String key = zone.get(i);
int j = i-1;
while(j>=0 && key.compareTo(zone.get(j)) > 0)
{
String x = zone.get(j+1);
zone.set(j, x);
j--;
}
String x = zone.get(j+1);
x = key;
}
}
public void printArrayOfZones()
{
System.out.println("The sorted words are");
for(ArrayList<String> zone:arrayOfZones)
{
for(String word: zone)
{
System.out.println(word);
}
}
}
阅读您的代码并查看您的结果,您的代码似乎覆盖了这些值而不是交换它们。 要解决此问题,您需要查看 function 排序。 我已经修改了您的代码,以便您交换两个元素,而不是覆盖:
private void sortZone(ArrayList<String> zone){
for(int i = 1; i < zone.size(); i++){
String key = zone.get(i);
int j = i-1;
while(j>=0 && key.compareTo(zone.get(j)) > 0){
String x = zone.get(j+1);
zone.set(j+1,zone.get(j)); // line added
zone.set(j, x);
j--;
}
String x = zone.get(j+1);
x = key;
}
}
我希望这解决了你的问题。
如果我将您的 sortZone 实现与参考插入排序实现(例如https://www.baeldung.com/java-insertion-sort )进行比较,我会看到以下差异 - 请参阅内联注释
for(int i = 1; i < zone.size(); i++)
{
String key = zone.get(i);
int j = i-1;
// The sort order is reversed.
// You've used "key > zone[j]" when it should be "key < zone[j]"
while(j>=0 && key.compareTo(zone.get(j)) < 0)
{
// This is copying items backwards, towards the beginning of the array.
// String x = zone.get(j+1);
// zone.set(j, x);
// It should be copying items forwards, towards the end, to make room for "key"
// Like this:
String x = zone.get(j);
zone.set(j+1, x);
j--;
}
// You should be setting zone[j+1] = "key" - this does not do it:
// String x = zone.get(j+1);
// x = key;
// This is how you set a value in a list:
zone.set(j+1, key);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.