Bubble Sorting (Java version)
Bubble Sort is a simple sorting algorithm. It repeatedly visits the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted. The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.
The Bubble Sorting Algorithm operates as follows:
Compares adjacent elements. If the first is bigger than the second, exchange the two of them. Perform the same operation on each adjacent element, from the first to the last. At this point, the final element should be the largest number.
Repeat the preceding steps for all elements except the last one. Continue to repeat the above steps for fewer and fewer elements until there is no need to compare them.
Package BubbleSort; import java. util. arrays; public class Demo01 {// the first version of static void BubbleSort (int [] arr) {int len = arr. length; for (int j = 0; j
Arr [I + 1]) {int temp = arr [I]; arr [I] = arr [I + 1]; arr [I + 1] = temp ;}} system. out. println (Arrays. toString (arr) ;}}// the second version reduces the number of times each trip. static void BubbleSortSecond (int [] arr) {int len = arr. length; for (int j = 0; j
Arr [I + 1]) {int temp = arr [I]; arr [I] = arr [I + 1]; arr [I + 1] = temp ;}} system. out. println (Arrays. toString (arr);} // Version 3/*** Final Version: assuming that the data is ordered, the latter is ordered after a trip, reduce the number of shards * For example, 81234 * First trip 12348 * second trip 12348 * @ param args */static void BubbleSortThird (int [] arr) {boolean sorted = true; int len = arr. length; for (int j = 0; j
Arr [I + 1]) {int temp = arr [I]; arr [I] = arr [I + 1]; arr [I + 1] = temp; sorted = false; // assume the failure} System. out. println (Arrays. toString (arr); if (sorted) {break ;}} public static void main (String [] args) {System. out. println ("=============== 1 ============="); int [] arr = {9, 2, 7, 3, 4}; BubbleSort (arr); System. out. println ("=============== 2 ==============="); arr = new int [] {9, 1, 7,3, 4}; BubbleSortSecond (arr); System. out. println ("=============== 3 ==============="); arr = new int [] {9, 1, 7,3, 4}; BubbleSortThird (arr );}}
Running result:
===========1============[2, 7, 3, 4, 9][2, 3, 4, 7, 9][2, 3, 4, 7, 9][2, 3, 4, 7, 9]===========2============[1, 7, 3, 4, 9][1, 3, 4, 7, 9][1, 3, 4, 7, 9][1, 3, 4, 7, 9]===========3============[1, 7, 3, 4, 9][1, 3, 4, 7, 9][1, 3, 4, 7, 9]