C language | insert a number into an array in order of size

Example 62: There is an array that has been sorted. After the C language is required to input a number, insert it into the array according to the original sorting rule.

Problem-solving ideas: Assuming that the array a has n elements, and they have been arranged in ascending order, the following methods are used when inserting a number:

If the inserted number num is greater than the last number in the a array, put the inserted number at the end of the a array.

If the inserted number num is not greater than the last number of the a array, it will be compared with a[0] a[n-1] in turn until a[i]>num appears, which means a[0] a[i -1] The value of each element is smaller than num, and the value of each element a[i]~a[n-1] is larger than num.

Source code demo:

#include<stdio.h>//头文件 
int main()//主函数 
{
    
    
  int a[11]={
    
    1,4,6,9,13,16,19,28,40,100};//定义整型数组且赋初值 
  int t1,t2,num,end,i,j;//定义整型变量 
  printf("原来的输出:\n");//提示语句 
  for(i=0;i<10;i++)//遍历输出10个数 
  {
    
    
    printf("%d ",a[i]);
  }
  printf("\n");//换行
  printf("输入要插入的数:\n");//提示语句 
  scanf("%d",&num);//键盘录入要插入的数
  end=a[9];//将最后一个数赋值给end 
  if(num>end)//先和最后一个数比大小 
  {
    
    
    a[10]=num;
  } 
  else
  {
    
    
    //小于的话,依次比较,直到比插入的数大 
    for(i=0;i<10;i++)
    {
    
    
      if(a[i]>num)
      {
    
    
        t1=a[i];
        a[i]=num;
        for(j=i+1;j<11;j++)
        {
    
    
          t2=a[j];
          a[j]=t1;
          t1=t2;
        }
        //把要插入的数放到数组中 
        break;
      }
    }
  }
  printf("插入之后排序:\n");//提示语句 
  for(i=0;i<11;i++)//遍历输出 
  {
    
    
    printf("%d ",a[i]);
  }
  printf("\n");//换行 
  return 0;//主函数返回值为0 
}

The compilation and running results are as follows:

原来的输出:
1 4 6 9 13 16 19 28 40 100
输入要插入的数:
8
插入之后排序:
1 4 6 8 9 13 16 19 28 40 100

--------------------------------
Process exited after 6.449 seconds with return value 0
请按任意键继续. . .

C language inserts a number into the array in order of size.
More cases can be Go Official Account: C language entry to proficient

Guess you like

Origin blog.csdn.net/weixin_48669767/article/details/112748276