合并排序将重复数据添加到Array

时间:2015-09-12 22:32:29

标签: java arrays sorting merge

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

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编程语言。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

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

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