Search code examples
javaarraylistinsertion

Insertion Sort Gone Wrong


I have an arraylist filled with random integers. I am trying to use insertion sort to sort and then print them on the screen. Everything works but the insertion sort... Not sure what is wrong can someone take a look at it and find what went wrong... Thanks.

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));
}

Solution

  • You are shadowing the oh variable.

    Inside the gen2 method, convert this

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

    To this

    oh = new ArrayList<Integer>();
    

    The reason it did not work, is because you declared a new ArrayList (named oh), whose scope was just inside the gen2 method. Removing the ArrayList , results in assigning the new ArrayList to the original class oh reference.