【问题标题】:Sort an array by name按名称对数组进行排序
【发布时间】:2015-05-13 11:52:27
【问题描述】:

我希望这些数据按名称排序,我正在使用以下代码,谁能告诉我它有什么问题?它没有完美地对数据进行排序。

条件是我们只能使用两个while和if循环。

             Sales and Commission
    ======================================================
     Salesperson        Sales Amount        Commission
    -----------------------------------------------------
    h h                 $54000          $4320.0 
    jghu jghf           $90000          $9000.0 
    hg gf               $45000          $2700.0 
    kaushal garg        $87000          $8700.0 
    kfhfuyd dhd         $32000          $1920.0 

     Total: 9 Data entries

代码:

public static void sortByName() {
    int small;      // Two while loop and one if loop for sorting 
    int i = 0;      // the data based on sales amount 
    while (i < name.length) {
        small = i;
        int index = i + 1;
        while (index < name.length) {

            if (name[index].compareToIgnoreCase(name[small]) < 0) { // name comparision for sorting
                small = index;
            }
            swap(i, small); // caling the swap method
            index++;

        }
        i++;
    }
    displayData();              // calling displayData function.
}

//Method used in the sorting the data based on name and sales
public static void swap(int first, int second) {
    String temp = name[first];
    name[first] = name[second];
    name[second] = temp;


}

【问题讨论】:

  • 你的名字数组是String[]吗?
  • 有必要使用数组吗?您还可以使用 ArrayList 并编写自定义 Comparator
  • “条件是我们必须使用两个 while 和 if 循环”:谁告诉你这个?顺便问一下,什么是 if 循环?
  • @user714965 可能是老师

标签: java arrays sorting


【解决方案1】:

我认为问题在于内部循环中的 swap 函数,因为它会一直执行。也许它应该发生在 if 范围内(不太确定,根据 compareToIgnoreCase() 函数的返回)。

while (index < name.length) {

            if (name[index].compareToIgnoreCase(name[small]) < 0) { // name comparision for sorting
                small = index;
                swap(i, small); // caling the swap method
            }

            index++;

        }

【讨论】:

    【解决方案2】:

    您似乎正在尝试实现冒泡排序。首先,没有“if-loop”之类的东西,它是一个 if 条件。我发现你的变量名很混乱,所以我重命名了其中的大部分。以下代码应该可以工作。

    public static void sortByName() {
        int i = 1;
        while (i < name.length) {
            int j = 0;
            while (j < name.length - i) {
                if (name[j].compareToIgnoreCase(name[j + 1]) > 0) {
                    //you should be able to figure out yourself, what to do here        
                }
                j++;
            }
            i++;
        }
        displayData();
    }
    

    【讨论】:

    • 很抱歉输入错误..我正在努力学习..感谢您的帮助
    • 你可以给你的变量任何你想要的名字。我只是无法理解您的代码;-)
    猜你喜欢
    • 1970-01-01
    • 2021-11-03
    • 2020-10-11
    • 2019-11-04
    • 2019-08-19
    • 1970-01-01
    • 2019-03-09
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多