Two day learning algorithm

Bubble sort

The core idea of ​​the bubble sort method: comparison of two numbers each adjacent, if they put them in the wrong order switching over, the smaller the more rearward. The main use of two-cycle algorithm.

Now, for example, the 10 digits, are 8 1,005,022,156,110,009,990 and a first comparison of the second digit, if an error, then the switch position, second comparing the second and third number, if an error is exchanged order. . . . . . . (Until relatively complete all the numbers)

Correct operation result is: 0,168,152,250,100,999 1000 using the following algorithm

#include <stdio.h>
 int main () 
{ 
  int A [ 100 ], I, J, T, n-; // T becomes a container for storing the exchange 
  Scanf ( " % D " , & n-); // input a the number n, the next n numbers 
  for (I = . 1 ; I <= n; I ++) // cycle number n is read into the array a 
        Scanf ( " % D " , & a [I]);
   // the core of the bubble sort 
  for (I = . 1 ; I <= N- . 1 ; I ++) // sort number n, n-1 only for times 
  for (J = . 1 ; J <= Ni; J ++) // from a comparison of the final number has not been homing until the first one, why think about 
what to N- i on it.
  {
        IF (A [J] <A [J + . 1 ]) // size comparison and exchange 
        {T = A [J]; A [J] = A [J + . 1 ]; A [J + . 1 ] = T;} 
  } 
} 

  for (I = . 1 ; I <= n-; I ++) // output 
       the printf ( " % D " , A [I]); 
  getchar (); getchar (); 
  return  0 ; 
}

 

Guess you like

Origin www.cnblogs.com/zjfman/p/11427033.html
Recommended