Bubble Sorting Algorithm Implementation

Source: Internet
Author: User
/*
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 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.