【问题标题】:Insertion Sort Gone Wrong插入排序出错
【发布时间】:2016-03-03 09:00:55
【问题描述】:

我有一个用随机整数填充的数组列表。我正在尝试使用插入排序进行排序,然后将它们打印在屏幕上。一切正常,但插入排序...不确定有什么问题,有人可以看看它并找出问题所在...谢谢。

public static  ArrayList<Integer> oh = new ArrayList<Integer>();

public static ArrayList<Integer> gen2()
{
    ArrayList<Integer> oh = new ArrayList<Integer>();
    Random random = new Random();
    for (int i = 0; i < 100; i++)
    {
        oh.add(random.nextInt());
    }
    return oh;
}

public static  ArrayList<Integer> insertionSort(ArrayList<Integer>oh) {
    int i, j;
    for (i = 1; i < oh.size(); i++) {
        Integer tmp = oh.get(i);
        j = i;
        while ((j > 0) && (oh.get(j - 1).intValue() > tmp.intValue())) {
            oh.set(j, oh.get(j - 1));
            j--;
        }
        oh.set(j, tmp);
    }
    return oh;
}

public static void main(String[] args)
{
    System.out.println("Original List:");
    System.out.println(gen2());
    System.out.println("Sorted Arraylist:");
    System.out.print(insertionSort(oh));
}

【问题讨论】:

    标签: java arraylist insertion


    【解决方案1】:

    您正在隐藏 oh 变量。

    在gen2方法里面,转换这个

    ArrayList<Integer> oh = new ArrayList<Integer>();
    

    到这里

    oh = new ArrayList<Integer>();
    

    它不起作用的原因是你声明了一个新的 ArrayList(名为 oh),它的作用域就在 gen2 方法内。删除 ArrayList 后,会将新的 ArrayList 分配给原始类哦参考。

    【讨论】:

    • @user5344755:在 Eclipse(也可能在其他 IDE:s 中)中,当您使用局部变量隐藏字段时,有一个设置可以针对这种情况启用警告。它真的有很多次帮助!位于首选项 -> Java -> 编译器 -> 错误/警告 -> 名称阴影和冲突中的设置。
    • @lii 谢谢我不知道!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多