/*
Basic Idea of Bubble Sorting
Regard N records as vertically arranged. When each sort is performed from bottom to top, the adjacent records are compared. If the order does not meet the requirements (in reverse order), the records are exchanged. At the end of each sort, the record with the smallest keyword in the sorting range can be raised to the corresponding position on the table like a bubble. The entire sorting process involves a total of N-1 queries, minimum, minimum, and third small keywords in sequence... The first, the second, and the third records of the "to" table... Location.
Initial model: 1st trips, 2nd trips, 3rd trips, 4th trips, 5th trips, 6th trips
38 12 12 12 12 12 12 12
20 38 20 20 20 20 20
46 20 38 25 25 25 25
38 46 25 38 38 38 38 38
74 38 46 38 38 38 38 38 38
91 74 38 46 46 46 46
12 91 74 74 74 74
25 25 91 91 91 91 91 91
*/
// Print Array
Void Printarray ( Int Array [], Int N)
{
IntI;
For(I=0; I<N; I++)
Printf ("% D", Array [I]);
Printf ("\ N");
}
// Bubble Sorting
Void Bubblesort ( Int Array [], Int N)
{
Int I = 0 ;
Int J = 0 ;
Int Temp = 0 ;
Int Flag = 0 ;
For (I = 0 ; I < N - 1 ; I ++ ) /* The total number of workers in sorting by the External Loop */
{
Flag = 0 ; /* The swap flag should be false before the sorting starts. */
For (J = N - 1 ; J > I; j -- ) /* Control the sorting by Loop */
{
If (Array [J] < Array [J - 1 ]) /* Compare Adjacent Elements and exchange them in reverse order. */
{
Temp = Array [J];
Array [J] = Array [J - 1 ];
Array [J - 1 ] = Temp;
Flag = 1 ; /* If an exchange occurs, the switch flag is set to true. */
}
}
If (Flag = 0 ) /* This sort order has not been exchanged and is terminated in advanceAlgorithm */
Break ;
/*
Printf ("% d sort result: \ n", I + 1 );
Printarray (array, N );
*/
}
}
Void Testbubblesort ()
{
Int Array [ 8 ] = { 38 , 20 , 46 , 38 , 74 , 91 , 12 , 25 };
Bubblesort (array, 8 );
Printarray (array, 8 );
}