Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - C language a question about arrays. . . Trouble
C language a question about arrays. . . Trouble
insert an integer into the sorted array in order of size.

in order to insert a number into an ordered array by size, you should first determine whether the sorting is from largest to smallest or from smallest to largest. If the sorting is from the largest to the smallest, the number to be inserted can be compared with the numbers in the array one by one. When the first element I smaller than the inserted number is found, it is the insertion position before. Then, from the last element of the array to that element, move back one unit one by one. Finally, the insertion number is given to the element I. If the inserted number is less than all the element values, the last position is inserted.

main()

{

int i,j,p,q,s,n,a[11]={127,3,6,28,54,68,87,15,162,18};

for(i=; i< 1; i++)

{ p=i; q=a[i];

for(j=i+1; j< 1; j++)

if(q< a[j]) {p=j; q=a[j]; }

if(p! =i)

{

s=a[i];

a[i]=a[p];

a[p]=s;

}

printf("%d ",a[i]);

}

printf("\ninput number:\n");

scanf("%d",& n);

for(i=; i< 1; i++)

if(n> a[i])

{for(s=9; s> =i; s--) a[s+1]=a[s];

break; }

a[i]=n;

for(i=; i< =1; i++)

printf("%d ",a[i]);

printf("\n");

}

This program first sorts the 1 numbers in array A from large to small and outputs the sorting results. Then enter the integer n to be inserted. Then use a for statement to compare n and array elements one by one. If n >; When a[i], the values of the elements below I are sequentially shifted back by one unit by an inner loop. The backward movement should be carried out from the back to the front (from a[9] to a[i]). Move back to end and jump out of the outer loop. The insertion point is I, just give n to a[i]. If all the elements are greater than the inserted number, the backward movement is not performed. At this time, i=1, and the result is to assign n to a[1]. The last loop outputs the values of the array elements after the inserted number.

when the program is running, enter the number 47. It can be seen from the results that 47 has been inserted between 54 and 28.