C Language Learning Tutorials fourth-arrays (7)

Source: Internet
Author: User
Tags arrays integer printf

Program examples

Inserts an integer into the sorted array in order of size. To insert a number into a sorted array by size, first determine whether the order is from large to small or large. To set the order from large to small, you can compare the number you want to insert with each number in the array, and when you find the first element I that is smaller than the number of inserts, that element is the insertion position. Then move one cell after another from the last element of the array to the element. Finally, the insertion number is given to the element I. Inserts the last position if the inserted number is smaller than all element values.
Main ()
{
int i,j,p,q,s,n,a[11]={127,3,6,28,54,68,87,105,162,18};
for (i=0;i<10;i++)
{P=i;q=a[i];
for (j=i+1;j<10;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=0;i<10;i++)
if (N>a[i])
{for (s=9;s>=i;s--) a[s+1]=a[s];
break;
A[i]=n;
for (i=0;i<=10;i++)
printf ("%d", a[i]);
printf ("\ n");
}
The program first sorts the 10 numbers in array a from large to small and outputs the sort results. then enter the integer n that you want to insert. Using a For statement to compare the N and array elements one by one, if there is a n>a[i], then an internal loop will move the value of the following elements into one unit. The backward move should be carried forward (from a[9] to a[i). The back end jumps out of the outer loop. The insertion point is I, and N is given to A[i]. If all elements are greater than the number of inserts, then the move does not work. At this time i=10, the result is to assign N to a[10]. The last loop outputs the element values of the array after the insertion number. When the program is running, enter the number 47. You can see from the results that 47 has been inserted between 54 and 28.

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.