Bubble sort (Bubble sort) is a simple sort algorithm. It repeatedly visited the sequence to sort, comparing two elements at a time, and swapping them out if they were wrong in the order. The work of the sequence of visits is repeated until no more need to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.
The bubbling sorting algorithm works as follows:
- Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
- Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
- Repeat the above steps for all elements, except for the last one.
- Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
Process diagram for bubbling sort:
Code:
[Java]View PlainCopyprint?
- Public class bubblesort{
- public static void Main (string[] args) {
- int score[] = {n/A, * *, * *, 100};
- For (int i = 0; i < score.length-1; i++) { //up to n-1 sequencing
- for (int j = 0; J < score.length-i- 1; j + +) { //Sort the current unordered interval score[0......length-i-1] (the scope of J is critical, this The circumference is gradually shrinking)
- if (Score[j] < Score[j + 1]) { //swap the small value to the back
- int temp = score[j];
- SCORE[J] = score[j + 1];
- Score[j + 1] = temp;
- }
- }
- System.out.print ("No." + (i + 1) + "Second order Result:");
- For (int a = 0; a < score.length; a++) {
- System.out.print (Score[a] + "\ t");
- }
- System.out.println ("");
- }
- System.out.print ("Final sorting Result:");
- For (int a = 0; a < score.length; a++) {
- System.out.print (Score[a] + "\ t");
- }
- }
- }
Reference: Http://zh.wikipedia.org/wiki/%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F
The results of the implementation are as follows:
[HTML]View PlainCopyprint?
- 1th time Sorted Results: 69 75 87 89 90 99 100 67
- 2nd time sorted Results: 75 87 89 90 99 100 69 67
- 3rd time Sorted Results: 87 89 90 99 100 75 69 67
- 4th time Sorted Results: 89 90 99 100 87 75 69 67
- 5th time Sorted Results: 90 99 100 89 87 75 69 67
- 6th time Sorted Results: 99 100 90 89 87 75 69 67
- 7th time Sorted Results: 100 99 90 89 87 75 69 67
- Final sort Result: 100 99 90 89 87 75 69 67
Java Bubble Sort