感觉好像我很接近,只是不知道在“If 语句”中放置什么以及事物的顺序。请帮忙。还不确定如何使用交换方法?
private static void selectionSort(String[] words, int numWords)
{
for (int i = 0; i < words.length; i++)
{
int min = i;
for(int j = i+1; j < words.length; j++)
{
if(words[index]<words[minIndex])
{
min = j;
}
swap(words, i, j);
}
}
}
public static int indexOfNextSmallest(String[] words, int startIndex)
{
int minIndex = startIndex;
for(int i = startIndex; i < words.length; i++) {
if(words[i].compareTo(words[minIndex]) < 0)
minIndex = i;
}
return minIndex;
}
private static void swap(String[] words, int i, int j)
{
String swap = words[i];
words[i] = words[j];
words[j] = swap;
}
尝试添加用户验证。想知道我应该在下面的方法中执行还是在主方法中执行?
private static int getMenuChoice(Scanner stdIn)
{
int option = 0;
System.out.println("\n1: Add Word");
System.out.println("2: Remove Word");
System.out.println("3: Print Words");
System.out.println("4: Quit");
System.out.print("Choose an option(1-4): ");
option = stdIn.nextInt();
return option;
}
最佳答案
您尝试使用 '<' 运算符比较 2 个字符串,但该操作不起作用。相反,您应该使用compareTo函数来比较两个可比较的对象。
if(words[index]<words[minIndex]) // doesnt work - Compilation error
{
min = j;
}
更改方法选择排序中的 if 条件,如下所示:
if(words[j].comapareTo(words[min]) < 0)
{
min = j;
}
此外,您需要交换索引 i 和 min 处的单词,而不是交换 i 和 j
swap(words, i, j); //wrong
swap(words, i, min); //correct - as it swaps min word & current word
关于java - 选择排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23551369/