Summary of Bubble sorting algorithms

Source: Internet
Author: User

The Bubble sorting algorithm is one of the simplest and most direct sorting methods.

After each traversal, a maximum (or minimum) number is bubble.

Pre-defined sorting type. To verify whether the sorting method is correct, we simply perform sorting detection on 10 elements. As follows:

 
# Define maxsize 10 typedef struct {int R [maxsize + 1]; int length;} sqlist; void swap (sqlist * l, int I, Int J) {int temp = L-> r [I]; L-> r [I] = L-> r [J]; L-> r [J] = temp ;}

Note: All sorting in this article is in ascending order.

The first one is a bit like the Bubble Sorting Algorithm for sorting:

This method is not a traditional bubble method. Traditionally, the bubble method compares and exchanges Adjacent Elements in the sorting array. This method compares and exchanges each element with the remaining elements. The Code is as follows:

 
Void bubblesort0 (sqlist * l) {int I, j; for (I = 0; I <L-> length-1; I ++) {for (j = I + 1; j <L-> length; j ++) {If (L-> r [I]> L-> r [J]) {swap (L, I, j );}}}}

2. Traditional Bubble sorting method:

 
Void bubblesort1 (sqlist * l) {int I, j; for (I = 0; I <L-> length; I ++) {for (j = 0; j <L-> length-I-1; j ++) {If (L-> r [J]> L-> r [J + 1]) {swap (L, J, J + 1 );}}}}

Third: improved Bubble sorting method

We know that in the Bubble Sorting Algorithm, even if the subsequent element sequence is already ordered and no comparison is required, the Bubble Sorting Algorithm will still be executed to the end. Can we improve it to avoid additional comparison operations when such a situation occurs?

You can set a flag. When no data is exchanged, the order is sorted. Then the algorithm stops running. The Code is as follows:

 
Void bubblesort2 (sqlist * l) {int I, j; bool flag = true; for (I = 0; I <L-> length & flag; I ++) {flag = false; For (j = 0; j <L-> length-1-i; j ++) {If (L-> r [J]> L-> r [J + 1]) {swap (L, J, J + 1 ); flag = true ;}}}}

 

References: big talk Data Structure

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.