C language insertion sorting

Source: Internet
Author: User

C language insertion sorting

The essentials of the insert sort method are to insert each read number to the final storage array immediately, and each insert will make the array orderly.

Code:

 

# Include

 
  
# Include

  
   
# Define n 10 int main () {int a [n] = {-1, 3, 6, 9, 13, 22, 27,32, 49 }; /* pay attention to leave a space for the number of to be inserted */int x, j, k; x = rand () % 100; printf ("the random value of x is: % d \ n ", x); if (x> a [N-2]) {a [n-1] = x; /* if it is greater than the last number, store it in the last element */} else/* find the location to be inserted */{j = 0; while (j <= n-2 & x> a [j]) {j ++;} for (k = n-2; k> = j; k --) {/* move one digit from the last digit until the number at the position to be inserted */a [k + 1] = a [k];} a [j] = x;/* Number of inserts to be inserted */} printf ("output: \ n"); for (j = 0; j <= n-1; j ++) printf ("% d", a [j]); return 0 ;}

  

 

Running result:

Randomly generate a number and insert it into the existing array. Sort the number and output it:

Related Article

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.