0

First of all, I'm writing program to visualize sorting algorithms on Android I wrote method for insertion sort algorithm. I'm using MPAndroidChart for it.

    void insertionSort(int[] arr) {
    int i, j, newValue;
    for (i = 1; i < arr.length; i++) {
        newValue = arr[i];
        j = i;
        while (j > 0 && arr[j - 1] > newValue) {
            arr[j] = arr[j - 1];
            j--;
        }
        arr[j] = newValue;
    }
}

...and it works fine. I want to redesign it to get the same result using ArrayList, but unfortunately, it crashes, and I have no idea why! This is my collection approach insertionSort:

void insertionSort(ArrayList<BarEntry> list) {
    int i, j;
    float newValue;
    for (i = 1; i < list.size(); i++) {
        newValue = list.get(i).getY();
        j = i;
        while (j > 0 && list.get(j-1).getY() > newValue) {
            list.set(j, list.get(j-1));
            j--;
        }
        BarEntry be = list.get(list.indexOf(newValue));
        list.set(j, be);
    }
}

BarEntry is class used to create charts. I want to sort my data by its Y coordinate, what I do by getY() function. Program shuts down there:

BarEntry be = list.get(list.indexOf(newValue)); list.set(j, be);

In a nutshell: How can I substitute

arr[j] = newValue;

to collection approach like this (not working):

list.set(j, list.get(list.indexOf(newValue)));

2
  • Are you getting an exception message? A stacktrace? Commented Jun 4, 2017 at 16:02
  • No, my app just getting restarted when I click button which call out my method. Commented Jun 4, 2017 at 16:04

2 Answers 2

1

You took newValue out from list.get(i), and i hasn’t changed since, so I believe you can just do that again:

    BarEntry be = list.get(i);

I have not tested.

I suppose what happened was: newValue was the y value from the BarEntry you are moving, it’s not the whole BarEntry. So list.indexOf(newValue) doesn’t find the element and returns -1. list.get(-1) doesn’t work. Your app crashes.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That was the solution!
0

From java doc

public void add(int index, E element)

Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

So no need to shift the rest of the array.

1 Comment

I have no idea how should it help me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.