首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择排序问题

选择排序问题
EN

Stack Overflow用户
提问于 2014-05-08 19:58:05
回答 1查看 40关注 0票数 0

感觉就像我离得这么近,只是不知道该把什么放在“如果状态”和事情的顺序上。请帮帮忙。也不确定用交换方法做什么好吗?

代码语言:javascript
复制
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;
}

试图添加用户验证。想知道我是应该用下面的方法来做,还是在主方法上做呢?

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-08 20:04:18

您正在尝试使用'<'运算符比较两个字符串,但该操作符不工作。相反,您应该使用compareTo函数来比较两个可比较的对象。

代码语言:javascript
复制
   if(words[index]<words[minIndex])   // doesnt work - Compilation error
   {
            min = j;
   }

在方法selectionSort中更改if条件如下:

代码语言:javascript
复制
    if(words[j].comapareTo(words[min]) < 0)
    {
            min = j;
    }

此外,您还需要在索引i& min处交换单词,而不是交换i&j。

代码语言:javascript
复制
  swap(words, i, j);  //wrong

  swap(words, i, min); //correct -  as it swaps min word & current word
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23551369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档