Bubble sort [simple complexity high]

Source: Internet
Author: User

The basic idea of bubble sorting is to compare two adjacent elements each time and swap them out if they are in the wrong order.


The principle of "bubble sort" is that each trip can only be determined by the return of one digit. That is, the first trip can only be determined to the last number (that is, the 5th digit), the second trip can only the number of the last 2nd digit (that is, 4th digit), the third trip can only be the number of the countdown 3rd (that is, the 3rd bit) to the place, sequentially.


Sum up: If there are n numbers to sort, just n-1 the number of digits, that is, to do a n-1 operation. and "Every trip" need to start from the 1th position of the adjacent two number of comparisons, the smaller one number in the back, after the comparison is done to move backward one to continue to compare the size of the following two adjacent numbers, repeat this step, until the last one has not been returned, the number has been returned no longer to compare.

#include <stdio.h> int main () {     int a[100],i,j,t,n;     scanf ("%d", &n); Enter a number n to indicate the next n number for    (i=1;i<=n;i++)//loop reads N to array a       scanf ("%d", &a[i]);     The core of the bubbling sort for    (i=1;i<=n-1;i++)//n is sorted by the number of n-1 trips    {for        (j=1;j<=n-i;j++)//starting from 1th to the last not yet returned, Think about why you can go to n-i.       {           if (a[j]<a[j+1])//compare size and swap          {t=a[j]; a[j]=a[j+1]; a[j+1]=t;}         }      }     for (i=1;i<=n;i++)//output result       printf ("%d", a[i]);      


Bubbling sorting solves the problem of wasting space in bucket sequencing. The core part of a bubbling sort is a double nested loop. It is not difficult to see that the time complexity of the bubbling sort is O (n^2). This is a very high degree of time complexity.

Bubble sort [simple complexity high]

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.