【问题标题】:Merge Sort adds duplicate data to Array合并排序将重复数据添加到数组
【发布时间】:2015-12-09 06:02:30
【问题描述】:

我正在使用 Java 尝试使用合并排序对对象的价格进行排序。我已经在另一段完美运行的代码中使用了合并排序,并且我使用该模型为我正在处理的另一个项目开发合并排序。但是,当我运行程序时,它不会输出 Array 中的所有项目,最终会复制一些项目。

TestItem.java

public static void sortPrice(Item[] it, int low, int high) {
    if (low == high) {
        return;
    }
    int middle = (low + high)/2;
    sortPrice(it, low, middle);
    sortPrice(it, middle + 1, high);
    merge(it, low, middle, high);
}

public static void merge(Item[] it, int l, int m, int h) {
    System.out.println(h-l+1);
    Item[] tmpItem = new Item[h - l + 1];
    int index = 0;
    int i = l, j = m + 1;
    while (i <= m || j <= h) {
        System.out.println(m);
        if (i > m) {
            tmpItem[index] = it[j];
            j++;
        } else if (j > h) {
            tmpItem[index] = it[i];
            i++;
        } else if (it[i].getPrice() > it[j].getPrice()) {
            tmpItem[index] = it[i];
            i++;
        } else {
            tmpItem[index] = it[j];
            j++;
        } 
        index++;
    }
    for (int k = l; k <= h; k++) {
        it[k] = it[k - l];
    }
}

当我运行将数组打印到控制台的方法 printInventory() 时,我希望看到如下所示的输出。

预期产量(按价格从高到低排序):

1201: Wrench Sets  Quantity Available: 55  Price: $80.0
1500: Ceiling Fans Quantity Available: 100 Price: $59.0   
1034: Door Knobs   Quantity Available: 60  Price: $21.5
1600: Levels       Quantity Available: 80  Price: $19.99
1011: Air Filters  Quantity Available: 200 Price: $10.5
1101: Hammers      Quantity Available: 90  Price: $9.99

实际输出:

1201: Wrench Sets  Quantity Available: 55  Price: $80.0
1034: Door Knobs   Quantity Available: 60  Price: $21.5
1600: Levels       Quantity Available: 80  Price: $19.99
1201: Wrench Sets  Quantity Available: 55  Price: $80.0
1034: Door Knobs   Quantity Available: 60  Price: $21.5
1600: Levels       Quantity Available: 80  Price: $19.99

项目在 Item.java

中声明

对不起,如果我犯了语法错误或引起混淆。我还在学习 Java 编程语言。感谢您的所有帮助!

【问题讨论】:

    标签: java arrays sorting merge


    【解决方案1】:

    代码从 it[] 合并到 tempItem[],所以最后一个 for 循环应该从 tmpItem[] 复制回 it[]:

        index = 0;        
        for(i = l; i <= h; i++)
            it[i] = tempItem[index++];
    

    【讨论】:

    • @TimothyRoeJr。 - 这是一个简单的错误。您可能需要考虑在调用代码中或在使用 tempItem[] 作为参数调用内部版本的合并排序的辅助函数中进行一次 tempItem[] (size = high - low + 1) 的分配。 sortPrice() 可以是分配 tempItem 的辅助函数,然后将其用作 mergesortPrice(it, low, high, tempItem) 的参数。不过对于这么小的数组来说没什么大不了的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    相关资源
    最近更新 更多