Home  >  Article  >  Backend Development  >  C language implements inserting a number into an ordered array and keeping it in order

C language implements inserting a number into an ordered array and keeping it in order

王林
王林Original
2020-05-08 13:37:067871browse

C language implements inserting a number into an ordered array and keeping it in order

Algorithmic idea:

Traverse from the beginning to find the first number that is greater than element, then insert the number, and the following elements will be moved in sequence.

Example code:

#include<stdio.h>//直接插入排序
void insert_array(int *a,int length,int element)//插入函数 往有序的数组a里插入值为element的元素使数组a依然有序 
{
  int i,j,t,f;
  for(i=0;i<length;i++)
  {
    if(a[i]>element)
       {
	    t=i;//找到位置以后 可以依次移动数组元素腾出位置了
         for(j=length;j>=t;j--)
            {
               if(j==t)
                   a[j]=element;
	       else
                  a[j]=a[j-1];//数组依次往后移动 不管正序还是倒序都可以
	    }
	    f=1;
	    break;
      }
      
     
   }
   if(f!=1)//当element大于所有数组元素时候
   {
     a[length]=element;
   }
  for(i=0;i<length+1;i++)
  {
    printf("%d ",a[i]);
  } 
}
int main()
{
  int a[5]={1,2,3,5,6};
  int e=7;
  insert_array(a,5,e);
}

Recommended tutorial:c language tutorial

The above is the detailed content of C language implements inserting a number into an ordered array and keeping it in order. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:what does c++ meanNext article:what does c++ mean