Issue Running Bubble Sort on Actor Array

Hey all. I’ve attempted to implement a bubble sort function using blueprint. The end goal is to sort an array of actors according to a variable inherent to each actor of the class called Agility in order to establish a turn order. I’m running into some difficulties and could use a helping hand.

The level I’m using to test the function has six children of the class placed into it: “Protagonist”, “Redman”, “Blugirl”, and three “EvilCubes”. Using The Get All Actors of Class Node and then printing the contents of the array results in this output:
image

“Protagonist” has a default Agility of 7, “Redman” has a default Agility of 5, “Blugirl” has 6, and the three “Evil Cubes” each have 3. Knowing this, if I run the Sort function and then print the output, the order should be Protagonist, Blugirl, Redman, Evil Cube, Evil Cube, Evil Cube. However, the actual output looks like:
image

It’s mostly correct, but Redman and Blugirl are out of the expected order.

Additionally, this error message is produced in the message log when running the code:

The following is my sort function in its current state:

I just have no idea where I went wrong. Anyone can recommend a fix for me?

That I can see:

  1. The last index of the for loop is 2 less than the array length. If n = 10, i < n - 1 is true until index 8. Same for second loop or it will go out of bounds.
  2. It should break the first loop on false, not on true:

For reference:

C++
// https://www.geeksforgeeks.org/bubble-sort/
void bubbleSort(std::vector<int>& arr) {
    int n = arr.size();
    bool swapped;
    for (int i = 0; i < n - 1; i++) {
        swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                std::swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        // If no two elements were swapped by inner loop, then break
        if (!swapped) {
            break;
        }
    }
}
BP


Hope it helps.

That seems to have fixed the issue. Thank you for the assist!

1 Like