冉冉说
#include <stdio.h>void f(int a[],int n,int k){int i,t; for(i=n-1;i>-1&&a[i]>k;i--) a[i+1]=a[i]; a[i+1]=k; }int main(){int n=10,i,k,a[15]={23,24,27,28,31,34,42,45,49,53}; for(i=0;i<n;i++) printf("%d ",a[i]); printf("\n"); scanf("%d",&k); f(a,n++,k); for(i=0;i<n;i++) printf("%d ",a[i]); printf("\n"); return 0; }
浮云间
//示例代码如下#include <stdio.h>#define N 100void f(int a[],int n,int k){ int *p,*q,*s; p=a; //指向首元素 while(p<p+n){ if(k>=*p && k<*(p+1)){ s=p+1; //指针s指向k待插入的位置 for(q=p+n-1;q>p;q--){ *(q+1)=*q; } *s=k; break; } p++; }}int main(){ int arr[N]; int n,i,value; scanf("%d",&n); printf("Input %d numbers: ",n); for(i=0;i<n;i++) scanf("%d",arr+i); printf("Insert a value: "); scanf("%d",&value); f(arr,n,value); printf("Output arr:\n"); for(i=0;i<n+1;i++) printf("%d ",arr[i]); printf("\n"); return 0;} //示例运行结果F:\c_work>a.exe5Input 5 numbers: 1 2 2 3 6Insert a value: 2Output arr:1 2 2 2 3 6 F:\c_work>a.exe5Input 5 numbers: 1 2 2 3 6Insert a value: 4Output arr:1 2 2 3 4 6 //修改了下的代码,现在没问题了,有问题的地方给你注释了#include <stdio.h>#include <stdlib.h>void f(int a[],int n,int k){int i,j,num;a[n]=k; //你这样赋值意味着数组的长度增加1了,即有(n+1)个元素了,数组末元素是a[n]//for(j=0;j<=n-1;j++)for(j=0;j<=n;j++){//for(i=j+1;i<n;i++)for(i=j+1;i<n+1;i++){if(a[j]>a[i]){num=a[j];a[j]=a[i];a[i]=num;} }}}int main(){int *a,n,i,k;printf("请输入数组长度:");scanf("%d", &n);if (n > 0){//a=(int *)malloc(n*sizeof(int));a=(int *)malloc((n+1)*sizeof(int));for(i=0;i<n;i++) {printf("请输入数组中第%d个数:\n",i+1);scanf("%d",&a[i]);}printf("请输入要插入的整数:");scanf("%d",&k);f(a,n,k);printf("升序排序后:");//for (i=0;i<n;i++)for (i=0;i<n+1;i++)printf("%d ",a[i]);printf("\n"); }}