Bubble sorting algorithm is a familiar algorithm, in our study of computer professional courses, in the textbook often meet to the program, as a very simple example of the program. If you can't write the algorithm, then you've never learned a computer-related course. All right, no more gossip.
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.
//bubble sort (decimal up, large number sinking) #include <stdio.h> typedef int Status; #define TRUE 1 #define FALSE 0//To re-sequence the integers in a
Ordered integer sequence void bubble_sort (int a[],int n) {int i,j,t) arranged into a large order; <span style= "color: #ff0000;"
>status change; </span> for (i=n-1,change=true;i>=1 && change;--i)//outer loop {<span style= "color: #ff0000;" >change=false;//Setting the change function is that when the sequence is ordered in advance, there is no further comparison, the sequence is already ordered </span> for (j=0;j<i;j++)//inner Loop {if (a[
J] > A[j+1])//The previous one is larger than the latter, moving backwards {t=a[j];
A[J]=A[J+1];
a[j+1]=t; <span style= "color: #ff0000;"
>change=true;//When a comparison occurs, set the change to TRUE if there is an exchange of elements </span>}}}}//print integer sequence void print (int r[],int n) {int i;
for (i=0;i<n;i++) {printf ("%d", r[i]);
} printf ("\ n");
} #define N 8 void Main () {int d[n]={49,38,65,97,76,12,27,49};
printf ("before sorting: \ n");
Print (d,n);
Bubble_sort (D,n);
printf ("After sorting: \ n");
Print (d,n); }
(1) Note that the program, a little bit of optimization, is to add a flag change, that is, in the inner layer of the loop after the comparison, if there is no exchange of elements to indicate that the sequence is already orderly, there is no need to carry out the outer loop.
(2) Bubble sort schematic diagram:
(3) Program operation Result: