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 bubble sort is called because the sort scan will always "take" the largest number from the ground, each time it sorts. The bubble sort is inefficient because it requires about N^2/2 comparisons, but for some decimals, its performance is acceptable. The name of the algorithm is because the larger the element will slowly "float" to the top of the sequence, hence the name.
Sequencing is very challenging in the program algorithm. The selection of the bubble algorithm is not very high efficiency, the actual need to sort the time is also relatively long, especially in the case of large amounts of data is more time-consuming.
The steps for the bubbling sorting algorithm are 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.
Repeat the above steps each time for less and fewer elements until there are no pairs of numbers to compare
Example:
#include <stdio.h>int main () {int i,j,n,temp,a[20];scanf ("%d", &n), for (i=0;i<n;i++) scanf ("%d", &a[i ]); for (i=1;i<n;i++) for (j=0;j<n-i;j++) if (a[j]>a[j+1]) {temp=a[j];a[j]=a[j+1];a[j+1]=temp;} for (i=0;i<n;i++) printf ("%d", A[i]); return 0;}
Time complexity O (n^2).
The bubble sort is to move the small element forward or the large element back. The comparison is an adjacent two element comparison, and the interchange also occurs between these two elements. So, if the two elements are equal, I think you will not be bored to exchange them again, if the two equal elements are not adjacent, then even through the preceding 22 exchange two adjacent together, this time will not be exchanged, so the same elements of the order has not changed, so bubble sort is a stable sorting algorithm.
Optimize:
Sets a tag flag,flag=0; indicates no interchange, flag=1; If the loop is not swapped, then the sort is complete.
<span style= "FONT-SIZE:18PX;" > #include <stdio.h>int main () {int i,j,n,temp,a[20],flag=0;scanf ("%d", &n), and for (i=0;i<n;i++) scanf ("% D ", &a[i]); for (i=1;i<n;i++) {flag=0; for (j=0;j<n-i;j++) if (a[j]>a[j+1]) {temp=a[j];a[j]=a[j+1];a[j+1]= Temp;flag=1;} if (flag==0) break;} for (i=0;i<n;i++) printf ("%d", A[i]); return 0;} </span>
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Internal sort (2)--bubble sort