The bubbling sort is each traversal. The comparison between adjacent numbers, the former greater than the latter to exchange, and constantly move the maximum value back to the last position; The key point of the algorithm is to determine the boundary of each cycle.
The following two algorithms are a certain degree of improvement to bubble sort, but the bubble sort performance is still poor compared with other sorting algorithms.
Bubble sort public class Bubble_sort {//The original solution public void Bubble_sort1 (int[] data) {int n = data.length;for (int i = 0; i < n; i++) {//Note the index range of the loop to avoid overflow for (int j = 0; J < n-i-1, j + +) {if (Data[j] > data[j + 1]) {Swap (data, J, j + 1);}}} Improved algorithms. Infer whether a loop has a movement by introducing a flag-volume flag. If there is no move, then//the order is complete, do not need to continue in the next cycle public void Bubble_sort2 (int[] data) {int n = Data.length;boolean flag = true;// Indicates whether the moving int index = n-1; Index of the last one that needs to be looped///once in motion. Then continue looping while (flag) {flag = false;for (int j = 0; J < Index-1; J + +) {if (Data[j] > data[j + 1]) {Swap (data, J, j + 1); FLA g = true;}} index--;}} Improved algorithm two: when a traversal. The last M-bit is not converted, it means that the next n bits are larger than the current maximum//according to the bubble sort, each sink in the maximum, then these bits must have been ordered public void Bubble_sort3 (int[] data) {int n = data.length ; int index = N-1;while (Index! = 0) {int k = 0;for (int j = 0; J < Index-1; J + +) {if (Data[j] > data[j + 1]) {Swap (dat A, J, J + 1); k = j;}} index = k;}} Cannot use reference implementations like C + +, so it is only good to use the data array to change private void swap (int[] data, int a, int b) {int temp = Data[a];d ata[a] = data[b];d ata[b] = TeMP;} public void Print_array (int[] data) {for (int num:data) {System.out.print (num); System.out.print ("");}} public static void Main (string[] args) {Bubble_sort bubble_sort = new Bubble_sort (); int data[] = {2,34,45,2,13,24,5,24,57} ; bubble_sort.bubble_sort3 (data); Bubble_sort.print_array (data);}}
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Bubble sort Algorithm (Java)