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