Reprint please indicate the source, thank you!
Bubble Sorting algorithm idea:
- Scan the record sequence from bottom to top (or up and down), and the adjacent two records
Ri
Ri-1
are swapped with (or Ri+1
) if in reverse order.
Exchange Sort
Algorithm Description
- An algorithm with a bad reputation
- The sort is stable.
ArrayList implementation:
import java.util.ArrayList;import Java.util.Random; Public classBubble { Public Static void Sort(Arraylist<integer> al) {intn = al.size(); for(inti = n-1; I >=0; i--) {BooleanFlag =false;//If the interchange does not occur in order to end the algorithm prematurely. for(intj = i; J >0; j--) {if(Al.Get(j) < Al.Get(j-1) {Integer Tempint = al.Get(j); Al.Set(J, Al.Get(j-1)); Al.Set(j-1, Tempint); Flag =true; }} System. out.println(AL);if(!flag) Break; } } Public Static void Main(string[] args) {//TODO auto-generated method stub intn =Ten; Arraylist<integer> Al =NewArraylist<> (n);//Create a random number generatorRandom Rand =NewRandom ();//Add 1-100 of random integers for(inti =0; I < n; i++) {al.Add(NewInteger (Math.ABS(Rand.Nextint( -)) +1)); } System. out.println("The ArrayList Sort before:\ n"+ Al +"\ nsorting: "); Bubble.Sort(AL); }}output:the ArrayList Sort before:[ the,7,8, the, A,6,3, -,Bayi, -]sorting:[3, the,7,8, the, A,6, -,Bayi, -][3,6, the,7,8, the, A, -,Bayi, -][3,6,7, the,8, -, the, A,Bayi, -][3,6,7,8, the, -, the, A,Bayi, -][3,6,7,8, the, -, the, A,Bayi, -]
--@guoyangde http://www.cnblogs.com/LittleTreasureBox/p/8904016.html
A sort algorithm of bad reputation (ii.)--bubble sort algorithm