Package?com.xingej.algorithm.sort.bubble;/**?*? Custom array classes? *?? * Features: With bubble sorting function?? *? Bubble sort Core: 1, from the last element of the array, start the comparison, 2, 22 comparison, meet the conditions, you need to do position exchange? * Real life: In primary school, you need to sort the seats according to your height, you can use bubble sort. *[email protected]?erjun?2017 December 11? Morning 9:20:28?*/public?class? Myarraywithbubblesort? {???? ? Declare an array???? Private?int[]?arr;???? An array of up to how many elements can be stored???? private?int?maxsize;???? How many elements are there in the current array; a bit similar to pointers, the meaning of the index???? private?int?elements;???? Public? Myarraywithbubblesort (int?maxsize)? {???????? this.maxsize?=?maxsize;???????? Arr?=?new?int[maxsize];???????? Initialize state, the number of default elements in the array is 0???????? this.elements?=?0,????}???? Public?void?insert (int?value)? {???????? Arr[elements++]?=?value,????}???? Public?void?show ()? {???????? For? (int?i?=?0;? i?<?elements;? i++)? {???????????? System.out.print (arr[i]?+ "?");????????}???????? System.out.println ();????}???? Public?void?bubblesort ()? {???????? 4?3?2?1, a 3-round comparison is required to sort by bubbling???????? For? (int?i?=?0;? I?<?elements?-? 1;? i++)? {???????????? For each round of comparisons, find the minimum value of this round???????????? For? (int?j?=?elements?-? 1;? j?>?i;? j--)? {???????????????? ? The blisters on the back/below are smaller than the blisters on the top, they shift???????????????? If? (arr[j]?<?arr[j?-? 1])? {???????????????????? Swap (j,?j?-? 1),????????????????}????????????}????????}????}???? The right and left value exchange???? Private?void?swap (int?i,?int?j)? {???????? ? java? is a reference delivery???????? Int?temp?=?arr[i];???????? ARR[I]?=?ARR[J];???????? arr[j]?=?temp;????}}
Unit tests:
Package?com.xingej.algorithm.sort.bubble;import?org.junit.test;public?class? Myarraywithbubblesorttest? {[email protected]???? Public?void?test ()? {???????? Myarraywithbubblesort?bubblesort?=?new? Myarraywithbubblesort (6);???????? Bubblesort.insert (2);???????? Bubblesort.insert (3);???????? Bubblesort.insert (1);???????? Bubblesort.insert (7);???????? SYSTEM.OUT.PRINTLN ("----------print out------before sorting");???????? Bubblesort.show ();???????? Bubblesort.bubblesort ();???????? SYSTEM.OUT.PRINTLN ("----------print output------after sorting");???????? Bubblesort.show ();????}}
Code has been managed to
Https://github.com/xej520/xingej-algorithm
The bubble sort of Java sorting algorithm