I have a small array of actors that should typically be under length 10, but can get up to 25 briefly, probably very rarely if at all over 50. I need them sorted by distance from an actor. My sort is very basic and just grabs the closest one and sets that one aside in a ranked array while removing it from the temp array, and this its iterated further until none are left in the temp array. So the iteration is ran a number of times equal to the length of the array.
I’m guessing this is poorly optimized, and this is a function that will run constantly roughly every .1 second, so I’m asking if I should go about this differently.
Yeah, you basically have to do this kind of thing.
You can save a write operation by only placing nearest ones in the output array, and then using = to overwrite the input array at the end. But that’s about it, I think…
What you have here is called a ‘bubble sort’. Quick sort is better, but more fiddly to program
I’m not sure I follow. The write operation I think you’re referring to comes before the pic and is a copying of the list of enemies. After the ordered array is full there is no additional write command on the initial array so if you’re saying to eliminate the temp array copy and then write the ordered array to the original array then wouldn’t that still be 1 write command just as my method? Sorry if I’m not being clear. If this is what you’re saying though, I’ll keep it in mind as I continue because I’m not sure currently where it will all lead and the change may apply well later.
I think ultimately, if this is an acceptable sort method, I will stick with it for now, as reading about sorting methods overwhelms me.
edit: Actually, I think I will remove the temp array copy and just copy to the input array afterward as it seems cleaner that way.
I did experiment with that first with a map with distances as keys but only tested that sorting the array output by “keys” did not sort the map and then I gave up on that approach, perhaps prematurely.