Example: Use the bubble sort method to sort 10 numbers in order from small to large.
int main ()
{
int i,j,t,a[10];
printf ("Input ten integers:\n");
for (i=0;i<10;i++)
scanf ("%d", &a[i]);
printf ("\ n");
for (j=0;j<9;j++)
for (i=0;i<9-j;i++)
if (a[i]>a[i+1])
{
T=a[i];
A[I]=A[I+1];
a[i+1]=t;
}
printf ("The sorted numbers:\n");
for (i=0;i<10;i++)
printf ("%4d", A[i]);
return 0;
}
Analysis:
- Compare the first number with the second number, in reverse order a[0]>a[1]. Then the second and third numbers are compared, and so on, until the first bubble is sorted by the number of n-1 and the nth number, the maximum number of results is placed in the last position.
- The second bubbling sequence of the number of previous n-1 results in the largest number being placed in the position of the first N-1 element.
- Repeat the above process, a total of n-1 order, the end of the sort.
Bubble Sort Method