C-Language implementation of bubble method ordering

Source: Internet
Author: User

First we look at the principle of bubble sorting, assuming there is an array of 6 numbers
The idea is: each time the adjacent two number comparison, will be small to the front, if there are 6 number: 8,7,5,4,2,0. The first two numbers 8 and 7 are swapped (see). The second and third numbers (8 and 5) are swapped ..... So total 5 times, get the order of 7-5-4-2-0-8, you can see: The largest number 8 has sink, becomes the bottom of a number, while the small number rises. After the first round (5 comparisons), the maximum number of 9 is obtained.


Then a second round of comparisons (see), a new round of comparisons of the remaining 7,5,4,2,0 to make the second-largest number sink. After this Round 4 times the comparison and the exchange, obtains the second big number 7.


According to this law, it can be inferred that 6 numbers need to compare 5 rounds, of which the first round needs to compare 5 times, the second round need to compare 4 times .... The fifth round needs to be compared only once.

If there is n number, you need to compare the n-1 wheel, in the first round is more important to do n-1 22 comparison, in the J round to conduct a n-j 22 comparison.

such as the bottom of the bubble gradually out of the water, so called bubble method.

The code is as follows:

#include <stdio.h>intMain () {intt,i,n,a[Ten];p rintf ("Please enter numbers:"); for(i=0;i<Ten; i++) scanf ("%d",&a[i]); for(i=0; i<=8; i++)     for(n=0;n<9-i;n++)        if(a[n]>a[n+1]) {T=A[n]; A[n]=a[n+1]; A[n+1]=T; }printf ("The sorted numbers is:"); for(i=0; i<=9; i++) printf ("%d\t", A[i]);return 0;}

C-Language implementation of bubble method ordering

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.