气泡排序对象

发布于 2025-01-21 12:18:57 字数 887 浏览 1 评论 0原文

我需要使用气泡排序来按名称对杂货清单进行排序。

显然,我的代码没有按名称对列表进行排序。
顺便说一句,数据存储的库存来自文件输入。

这是我的代码。

public void sortInventoryByName() {
    //TODO: use bubble sort and compareTo
    int n = inventory.size();
    GroceryItem temp;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (inventory.get(j).compareTo(inventory.get(j + 1)) > 0) {
                temp = inventory.get(i);
                inventory.set(i, inventory.get(i + 1));
                inventory.set(i + 1, temp);
            }
        }
    }
}

这是我的超级类(杂货店)的比较方法

@Override
public int compareTo(Object o) {
    if(getClass() != o.getClass()) {
        throw new IllegalArgumentException();
    }
    else {
        GroceryItem other = (GroceryItem) o;
        return (this.name.compareTo(other.name));
    }
}

I need to sort my grocery inventory by name by using bubble sort.

Apparently, my code is not sorting the list by name.
BTW, the data stored inventory comes from a file input.

Here is my code.

public void sortInventoryByName() {
    //TODO: use bubble sort and compareTo
    int n = inventory.size();
    GroceryItem temp;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (inventory.get(j).compareTo(inventory.get(j + 1)) > 0) {
                temp = inventory.get(i);
                inventory.set(i, inventory.get(i + 1));
                inventory.set(i + 1, temp);
            }
        }
    }
}

Here is my compareTo method from my superclass (GroceryItem)

@Override
public int compareTo(Object o) {
    if(getClass() != o.getClass()) {
        throw new IllegalArgumentException();
    }
    else {
        GroceryItem other = (GroceryItem) o;
        return (this.name.compareTo(other.name));
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

往事风中埋 2025-01-28 12:18:57

看起来您有一些不匹配以比较正确的值。

对于LOOPS ,有两种用两种用两个实现气泡排序算法的方法。

下面使第一个循环增加了屏障变量,第二个是减少index

因此,随着外循环的每一次迭代,最低的值将被移至第一名(例如,最小气泡将首先移动)。下一个迭代将跳过第一个元素。它将持续到列表完整列表将结束为止。

您的示例显示相反的行为 - &GT;对于外循环的每一次迭代,列表中的最高元素都移至末尾。

您要确切要迭代内部循环并不重要。最终的排序结果是我们的目标。

代码段:

public void sortInventoryByName() {
    int n = inventory.size();
    for (int barrier = 0; barrier < n - 1; barrier++) {
        for (int index = n - 2; index >= barrier; index--) {
            if (inventory.get(index).compareTo(inventory.get(index + 1)) > 0) {
                GroceryItem temp = inventory.get(index);
                inventory.set(index, inventory.get(index + 1));
                inventory.set(index + 1, temp);
            }
        }
    }
}

您的compareTo()的实现应正常工作。因此,库存列表应正确排序。

根据您的代码,一些通知:

  • 您无需在循环之外声明temp变量。它只是交换两个值的临时变量。内联声明和用法就足够了。

  • 建议为循环变量添加更有意义的名称,而不是ij。它增加了未来的代码可读性和理解

  • else块是多余的,在comparpoto()

@Override
public int compareTo(Object o) {
    if (getClass() != o.getClass()) {
        throw new IllegalArgumentException();
    }
    GroceryItem other = (GroceryItem) o;
    return this.name.compareTo(other.name);
}

Looks like you have some mismatch for comparing the right values.

There are two ways of implementing a bubble sort algorithm with two for loops.

Below made the first loop incremented barrier variable and second is decrementing index.

Thus with every iteration of the outer loop, the lowest value will be moved to the first place (like the smallest bubble will be moved first). The next iteration will skip this first element. And it will last till the list full list will be over.

Your example shows opposite behaviour -> with every iteration for the outer loop the highest element in a list is moved to the end.

It isn't so important how exactly do you want to iterate the inner for loop. The final sorted result is our aim.

Code snippet:

public void sortInventoryByName() {
    int n = inventory.size();
    for (int barrier = 0; barrier < n - 1; barrier++) {
        for (int index = n - 2; index >= barrier; index--) {
            if (inventory.get(index).compareTo(inventory.get(index + 1)) > 0) {
                GroceryItem temp = inventory.get(index);
                inventory.set(index, inventory.get(index + 1));
                inventory.set(index + 1, temp);
            }
        }
    }
}

Your implementation of compareTo() should work fine. So, inventory list should be sorted correctly.

A few notices according to your code:

  • you don't need to declare temp variable outside of loops. It is just a temporary variable for swapping two values. Inline declaration and usage will be enough.

  • would suggest adding more meaningful names for loop variables instead of just i and j. It increases code readability and understanding in the future

  • else block is redundant at compareTo()

@Override
public int compareTo(Object o) {
    if (getClass() != o.getClass()) {
        throw new IllegalArgumentException();
    }
    GroceryItem other = (GroceryItem) o;
    return this.name.compareTo(other.name);
}
始终不够爱げ你 2025-01-28 12:18:57

我填写了您的代码缺失部分。您应该阅读我如何问一个好问题,以及如何创建一个最小的,可重复的示例

以下代码是GroceryItem类,该类仅包含一个成员,即name,这是杂货项目的名称。由于您的问题仅涉及操纵该成员,因此我没有尝试猜测课程需要什么。

代码后的说明。

import java.util.ArrayList;
import java.util.List;

public class GroceryItem implements Comparable<GroceryItem> {
    private String  name;

    public GroceryItem(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override // java.lang.Comparable
    public int compareTo(GroceryItem other) {
        if (other == null) {
            return 1;
        }
        else {
            String otherName = other.getName();
            if (name == null) {
                if (otherName == null) {
                    return 0;
                }
                else {
                    return -1;
                }
            }
            else {
                if (otherName == null) {
                    return 1;
                }
                else {
                    return name.compareTo(otherName);
                }
            }
        }
    }

    @Override // java.lang.Object
    public boolean equals(Object other) {
        boolean equal = false;
        if (other instanceof GroceryItem) {
            GroceryItem otherItem = (GroceryItem) other;
            if (name == null) {
                equal = otherItem.getName() == null;
            }
            else {
                equal = name.equals(otherItem.getName());
            }
        }
        return equal;
    }

    @Override // java.lang.Object
    public int hashCode() {
        return name == null ? 0 : name.hashCode();
    }

    @Override // java.lang.Object
    public String toString() {
        return name;
    }

    public static void main(String[] args) {
        List<GroceryItem> inventory = new ArrayList<>();
        inventory.add(new GroceryItem("apple"));
        inventory.add(new GroceryItem("pear"));
        inventory.add(new GroceryItem("banana"));
        inventory.add(new GroceryItem("orange"));
        inventory.add(new GroceryItem("beetroot"));
        inventory.add(new GroceryItem("onion"));
        inventory.add(new GroceryItem("lettuce"));
        inventory.add(new GroceryItem("carrot"));
        inventory.add(new GroceryItem("guava"));
        inventory.add(new GroceryItem("lychee"));
        inventory.add(new GroceryItem("kiwi"));

        int n = inventory.size();
        for (int i = 0; i < n-1; i++) {
            for (int j = 0; j < n-i-1; j++) {
                if (inventory.get(j).compareTo(inventory.get(j+1)) > 0) {
                    // swap inventory[j+1] and inventory[j]
                    GroceryItem temp = inventory.get(j);
                    inventory.set(j, inventory.get(j+1));
                    inventory.set(j+1, temp);
                }
            }
        }
        System.out.println();
    }
}

上面的代码创建list GroceryItem包含11个元素的对象。填充列表后, bubble Sort 将在两个中执行循环的嵌套。最后,打印了排序<代码>列表

请注意,类GroceryItem还实现方法toString(),以便在打印groceryItem的实例时使输出人类可读。

如果将来,您需要使用groceryItem作为java.util.hashmap的键,则groceryItem将需要覆盖方法< code> hashcode(),如果类覆盖方法hashcode(),则它也应覆盖方法equals()。因此,这就是为什么上述代码包括那些覆盖方法的原因。请注意,这些方法都不是 - equals()hashcode()toString() - - bubble Sort < /em>。

运行上述代码时的oputput是:

[apple, banana, beetroot, carrot, guava, kiwi, lettuce, lychee, onion, orange, pear]

I filled in the missing parts of your code. You should read How do I ask a good question and also the link to How to create a Minimal, Reproducible Example.

The below code is the GroceryItem class which only contains a single member, i.e. name, which is the name of the grocery item. Since your question only deals with manipulating this member, I did not try to guess what other data the class needs.

Explanations after the code.

import java.util.ArrayList;
import java.util.List;

public class GroceryItem implements Comparable<GroceryItem> {
    private String  name;

    public GroceryItem(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override // java.lang.Comparable
    public int compareTo(GroceryItem other) {
        if (other == null) {
            return 1;
        }
        else {
            String otherName = other.getName();
            if (name == null) {
                if (otherName == null) {
                    return 0;
                }
                else {
                    return -1;
                }
            }
            else {
                if (otherName == null) {
                    return 1;
                }
                else {
                    return name.compareTo(otherName);
                }
            }
        }
    }

    @Override // java.lang.Object
    public boolean equals(Object other) {
        boolean equal = false;
        if (other instanceof GroceryItem) {
            GroceryItem otherItem = (GroceryItem) other;
            if (name == null) {
                equal = otherItem.getName() == null;
            }
            else {
                equal = name.equals(otherItem.getName());
            }
        }
        return equal;
    }

    @Override // java.lang.Object
    public int hashCode() {
        return name == null ? 0 : name.hashCode();
    }

    @Override // java.lang.Object
    public String toString() {
        return name;
    }

    public static void main(String[] args) {
        List<GroceryItem> inventory = new ArrayList<>();
        inventory.add(new GroceryItem("apple"));
        inventory.add(new GroceryItem("pear"));
        inventory.add(new GroceryItem("banana"));
        inventory.add(new GroceryItem("orange"));
        inventory.add(new GroceryItem("beetroot"));
        inventory.add(new GroceryItem("onion"));
        inventory.add(new GroceryItem("lettuce"));
        inventory.add(new GroceryItem("carrot"));
        inventory.add(new GroceryItem("guava"));
        inventory.add(new GroceryItem("lychee"));
        inventory.add(new GroceryItem("kiwi"));

        int n = inventory.size();
        for (int i = 0; i < n-1; i++) {
            for (int j = 0; j < n-i-1; j++) {
                if (inventory.get(j).compareTo(inventory.get(j+1)) > 0) {
                    // swap inventory[j+1] and inventory[j]
                    GroceryItem temp = inventory.get(j);
                    inventory.set(j, inventory.get(j+1));
                    inventory.set(j+1, temp);
                }
            }
        }
        System.out.println();
    }
}

The above code creates a List of GroceryItem objects that contains eleven elements. After populating the List, the bubble sort is performed in the two, nested for loops. Finally the sorted List is printed.

Note that class GroceryItem also implements method toString() so as to make the output human-readable when printing an instance of GroceryItem.

If, in future, you need to use GroceryItem as the key for a java.util.HashMap, then GroceryItem will need to override method hashCode() and if a class overrides method hashCode() then it should also override method equals(). Hence that is why the above code includes those overridden methods. Note that none of those methods – equals(), hashCode() and toString() – are required for the bubble sort.

The oputput when running the above code is:

[apple, banana, beetroot, carrot, guava, kiwi, lettuce, lychee, onion, orange, pear]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文