Bubble sorting a Java array is a very good way to get practice with arrays. It shows many techniques and here I will show one. It doesn't give graphical representation, but it gets the job done. The compiler does a little extra work (as this is designed to be a beginning tutorial and answer to the basic bubble sort algorithm.) The basic concept behind a bubble sort is that we test each digit of the array once, swapping (hence moving) the higher digit to the right.we will do this one time for every digit in the array. The final result is a sorted array ascending.
Lets look at an array 2, 3, 1. It starts with 2, and tests it against 3. If 2 is greater than three it swaps them, but 2 isn't greater... we just move on. It then tests 3 against 1, which is higher (hence swapping the 3 and 1). The resulting array is 2, 1, 3. We do this one more time, resulting in 1, 2, 3. Here is the code:
In plain English, the above example calls out a swap routine, sending the routine the array and the value which is going to get swapped with the one to the right of it in the array; it is also notable to see that we are returning the full array with the swapped values. Here is the function to swap, and therefore bubble sorting and that is:
And this is added directly below the main function. You can see that it also closes out the class. For added verification, you may want to print the array, but I will leave that for another day. In the next issue of Java programming, I will go over a better sorting routine that will not require this many steps.
Technorati Tags:
Java,
Tutorial