Package com.java.base.sort.algorithm;/** * Bubble Sort * * <p> algorithm ideas: * * <p>1. Start with the first number of numbers, compare the two numbers per adjacent, and swap the larger (or smaller) number to the back, Until the largest number is exchanged to the last of the series * * <p>2. The first step in the loop until the first number is left in the sequence. * Algorithm complexity: O (n2) * Stability: Stable * * @author lxy */public class Bubblesort {/** * Exchange */private static void Swap (int[] array, int m, int n) {int tmp = array[m]; ARRAY[M] = Array[n]; Array[n] = tmp; }/** * Bubble sort: 9,8,11,17,12,2,4,5,20,3,1 */public static int[] Bubblesort (int[] array) {if (array = = NULL | | arra Y.length = = 0) {throw new IllegalArgumentException ("Array must is not empty!"); } if (array.length = = 1) {return array; } for (int i = array.length-1; i > 0, i--) {for (int j = 0; J < i; J + +) {if (Array[j] > array[ J + 1]) {Swap (array, J, j + 1); }}} return array; }/** * Test */public static void main (string[] args) {int[] array = {9, 8, 11, 17, 12, 2, 4, 5, 20, 3, 1}; System.out.println ("bubble sort Before:"); for (iNT i = 0; i < Array.Length; i++) {System.out.print (array[i]); System.out.print (","); } array = Bubblesort.bubblesort (array); System.out.println ("\ n bubble sort:"); for (int i = 0; i < Array.Length; i++) {System.out.print (array[i]); System.out.print (","); } }}
Execution Result:
冒泡排序前:9,8,11,17,12,2,4,5,20,3,1,冒泡排序后:1,2,3,4,5,8,9,11,12,17,20,
Sort algorithm--bubble sort