Suppose you want to sort the sequence with n number in ascending order, the bubble sort algorithm step is:
1, starting from the first element in the array of storage sequence to the last element, in turn, the adjacent two numbers are compared, if the former large latter small, then the position of exchange two number;
2. At the end of the 1th trip, the maximum number is stored in the last element of the array, then the first element starts to the penultimate element, then the adjacent two numbers are compared, and if the former is smaller, the position of two digits is exchanged;
3, repeat step 1 n-1 trip, each trip than the previous trip less than once, you can complete the request.
Example 1, randomly generated 10 100 or less, the bubble method in ascending order after the output.
#include <stdio.h> #include <stdlib.h> #define N x int main (void) {int a[n],i,j,t; printf ("randomly produces 10 or less 100: \ n "); for (i=0;i<n;i++) { A[i] = rand ()%100; printf ("%d\n", A[i]); } printf ("Output: \ n"); for (j=1;j<=n-1;j++) { /*n number of processing n-1 * /for (i=0;i<=n-1-j;i++) { /* per trip less than the previous trip */ if (A[i] >a[i+1]) { t=a[i]; A[I]=A[I+1]; a[i+1]=t;} } }for (i=0;i<n;i++) {printf ("%d\n", A[i]);} return 0;}
Operation Result:
The bubble sort of C language