C语言:一个排好序的数组,现输入一个数,要求按原来规律将它插入到数组中

如题,在写的时候麻烦加一下注释,新手不太懂,谢谢了。。。。。。。。。。。。。

你就写一个循环就可以啊,找一下新加入的数处于那两个数中间,放在那个位置就可以



int main()
{
int i,num,a[11]={10,20,30,40,50,60,70,80,90,100};
scanf("%d",&num);

printf("\n");
for (i=9;i>=0;i--)
{
if (a[i] > num)
{
a[i+1]=a[i];

           if(a[i==0]>num)
           {a[i]=num;}
         } 



           else
           {
           a[i+1]=num;
           break;
           }
    } 



  for(i=0;i<11;i++)
  {
  printf("%d\n",a[i]);                
  }
  getch();

}


解释下这个代码

从数组最后一个元素开始,往后移动一个,直到找到要插入的数字,要插入的数字直接插入,然后完成。

举例,10 20 30 40 50 60 70 80 90 100,插入37
第一次循环
10 20 30 40 50 60 70 80 90 100 100
第二次
10 20 30 40 50 60 70 80 90 90 100
第三次
10 20 30 40 50 60 70 80 80 90 100
...
第七次
10 20 30 40 40 50 60 70 80 90 100
第八次
10 20 30 37 40 50 60 70 80 90 100,然后break
完成

就是一个数组排序的问题,建议自己写写,多写多看才能学好
http://blog.csdn.net/albinzhiyu/article/details/6603948

选择排序就可以解决,欢迎来我博客看看排序,有实现的源代码

主要是弄明白原来的规律是什么?是从小到大、从大到小、先奇后偶、先偶后奇、先质数后合数....重要的是原理的规律。

#include "stdio.h"
int main() {
int a[8] = {1, 2, 3, 4, 6, 7, 8};
int i, x, tmp, p = 7;
scanf("%d", &x);
a[7] = x;//把x加到末尾,a数组为 {1 2 3 4 6 7 8 x}
while (p && a[p] < a[p - 1]) { //p最开始指向末尾,如果p前面还有数且比p要小
tmp = a[p];//那么交换p和它前面的数
a[p] = a[p - 1];
a[p - 1] = tmp;
p--;//p向前挪一位
}
for (i = 0; i < 8; i++) {
printf("%d%c", a[i], " \n"[i == 7]);
}
}

 #include<stdio.h>
int main(){
    int s;
    scanf("%d",&s);   //get the number you shouldinsert
    int n;
    scanf("%d",&n);   //the number of the element of the initial array

    int digit[n],i,record=0;   //create an array and create an variable control the loop

    for(i = 0;i < n;i++)
    scanf("%d",&digit[i]);    //initialision you are supposed to make it in order from little to large

    for(i=0;i<n;i++){
        if (s>digit[i]&&s<digit[i+1]){

        record=i;
        break;}
    } 
    record++;
    printf("%d",record);

    return 0;


}

输出的值record表明插入至第record与record+1中间