In my previous game Pirates Jewels I use a bubble sort at certain points in the game, and I decided to work on an improved bubble sort that fit certain criteria:
1: This is a specialized bubble sort where '0' numbers float to the top and the rest of the numbers sink down and stay in their previous order
2: The first improvement is I want to be able to pass an array to the function rather than hard coding it to always use one particular array.
3: The second improvement is I want it to accept variable length arrays ; that is it should automatically traverse the array for the length of the passed array.
4: The third improvement is if no swapping occurred on an given pass it should break through the current inner for loop and out to the next outer loop (speeds up processing that is otherwise unnecessary)
So I wrote it in Java because I'm learning Java .. I do everything first in Java right now to improve my skills there.
BUT I need this to work in C++ because right now I am using the AppGameKit by The Game Creator's and I have to write this in C++ to get it to port to iOS AND Android at the same time.
So here is my Java code (that works fine!)
public static int[] zeroOnlyBubbleSort(int[] array){
boolean needNextPass = true;
for(int k =1; k < array.length && needNextPass; k++){
needNextPass = false;
for(int i = 0; i < array.length - k; i++) {
if (array[i] != 0 && array[i +1] == 0){
int temp = array[i];
array[i] = array[i+1];
array[i+1]= temp;
needNextPass = true;
}
}
}
return array;
}
I have done some googling and I am not finding any solutions that match the simple elegance of the Java approach?
Any suggestions ?
Post a comment!
No comments:
Post a Comment