C-Inserts a number into a sorted array, and the array remains sorted after insertion

Source: Internet
Author: User

Overview

Since this is just a demo of inserting 1 numbers, here I do not have malloc to redistribute again, but instead of freeing up a placeholder for the original array.

The complete code is as follows:

1#include <stdio.h>2 3 #defineLEN 6//the length of the array.4 5 /*6 title: There is an array that has been sequenced. Now enter a number that requires it to be inserted into the array as it was originally.7 Program Analysis: First determine whether this number is greater than the last number, and then consider inserting the middle number of cases, after inserting this element after the number, and then move back one position. 8 */9 Ten //Returns the subscript that will be inserted into the array. One int  AIndextoinsert (int*a,intkey) { -     //The subscript of the last number of the index of the original array is: LEN-2. -      for(inti = LEN-2; I >=0; i--) { the         if(Key >=A[i]) -             returni +1;//Insert the back of the number labeled I. -     } -     return 0;//The number to be inserted is smaller than the value in the array.  + } -  + void AInsertint*a,intkey) { at     intindex =Indextoinsert (A, key); -      for(inti = LEN-2; I >= index; i--)//Shifts the number of subscripts to the end of the index to the second. -A[i +1] =A[i]; -A[index] = key;//inserts the specified value. - } -  in //Print. - void toShowint*a) { +      for(inti =0; i < LEN; i++) -printf"%d", A[i]); theprintf"\ n"); * } $ Panax Notoginseng int -Mainvoid) { the     intA[] = {1,2,3,5,6,' /'};//the last number is a placeholder. +     intKey =4;//Insert 4. A Insert (A, key); the Show (a); +printf"\ n"); -}

C-Inserts a number into a sorted array, and the array remains sorted after insertion

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.