The bubble sort of C language

Source: Internet
Author: User

Suppose you want to sort the sequence with n number in ascending order, the bubble sort algorithm step is:

1, starting from the first element in the array of storage sequence to the last element, in turn, the adjacent two numbers are compared, if the former large latter small, then the position of exchange two number;

2. At the end of the 1th trip, the maximum number is stored in the last element of the array, then the first element starts to the penultimate element, then the adjacent two numbers are compared, and if the former is smaller, the position of two digits is exchanged;

3, repeat step 1 n-1 trip, each trip than the previous trip less than once, you can complete the request.

Example 1, randomly generated 10 100 or less, the bubble method in ascending order after the output.

#include <stdio.h> #include <stdlib.h> #define N x int main (void) {int a[n],i,j,t; printf ("randomly produces 10 or less 100: \ n "); for (i=0;i<n;i++) {   A[i] = rand ()%100;   printf ("%d\n", A[i]); } printf ("Output: \ n");  for (j=1;j<=n-1;j++)  {     /*n number of processing n-1 *    /for (i=0;i<=n-1-j;i++) {    /* per trip less than the previous trip */      if (A[i] >a[i+1])   {     t=a[i];    A[I]=A[I+1];    a[i+1]=t;}   } }for (i=0;i<n;i++) {printf ("%d\n", A[i]);} return 0;}


Operation Result:




The bubble sort of C language

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.