将一个任意一个整数插入到已排好序得数组中,插入后,数组中的数仍然保持有序。
要求:
1整型数组直接赋值的方式初始化,要插入的数组用scanf函数输入;
2算法过程用指针处理
3输出原始数组数据以及插入后的数组数据,并加以说明。
快点。。
int main(void){
int arr[10]={2,7,9,11,15,27,29,32,35,36};
int cp[100]={}; //新数组
int val=0;
int *p=arr;
int firstflag=0; //插入标志,若=1表示已插入
printf("请输入要插入的数:");
scanf("%d",&val);
int i;
for(i=0;i<10;){ //一次循环
if(firstflag==0){ //如果还没有插入
if(val<*p){ //如果要插入的数小于循环的数,就将插入的数放入新数组中
cp[i]=val;
i++;
firstflag=1;
}
else{ //如果插入的数大于循环所得的数,将原数组中对应的数放入新数组中
cp[i]=*p;
p++;
i++;
}
}
else{ // 如果已插入,则将原数组中的数放入新数组中
cp[i]=*p;
p++;
i++;
}
}
printf("原始数组:\n");
for(i=0;i<10;i++){
printf("%d ",arr[i]);
}
printf("\n");
printf("插入后的数组:\n");
for(i=0;cp[i];i++){
printf("%d ",cp[i]);
}
printf("\n");
}
结果:
请输入要插入的数:9
原始数组:
2 7 9 11 15 27 29 32 35 36
插入后的数组:
2 7 9 9 11 15 27 29 32 35
请输入要插入的数:16
原始数组:
2 7 9 11 15 27 29 32 35 36
插入后的数组:
2 7 9 11 15 16 27 29 32 35
根据你的要求,已经完成:
说明:
程序的核心思想就是:首先定位x在数组中的位置(利用二分查找实现)pos,然后根据位置,对数组元素依次进行逆序移动,最后腾出1个空间,插入x。程序配有详细注释,以帮助LZ理解程序思想。
1 程序中,x即为待插入的整数。
2 本程序函数分工明确:
Locate_X():定位x在数组中的位置。
Insert_X():插入到数组中。
pirint_Arr():打印数组。
代码如下:
#include<stdio.h>void Locate_X(int x, int *pos, int *a);
void Insert_X(int x, int pos, int *a);
void print_Arr(int *arr);
/*a[]的最后一个-1是为将来插入时保留的位置*/
int a[21] = { 1, 21, 44, 75, 96,
102, 198, 257, 369, 400,
499, 543, 577, 649, 701,
702, 776, 871, 888, 923,
-1};
/*len为a[]的有效长度*/
int len = 20;
int main()
{
int x,pos;
printf("input x: ");
scanf("%d",&x);
print_Arr(a);
Locate_X(x, &pos, a);
Insert_X(x, pos, a);
print_Arr(a);
return 0;
}
/*定位:x将要插入到a的位置*/
void Locate_X(int x, int *pos, int *a)
{
int i=0;
int low=0, high=len-1, mid;
if(x > a[high]) { *pos = len; return; }/*插入首部*/
if(x < a[low] ) { *pos = 0 ; return; }/*插入尾部*/
do{
mid = (high + low) / 2;
if(x > a[mid] )
{
low = mid; /*与一般的折半查找不同,这里是mid,而不是mid+1*/
}
else if(x < a[mid])
{
high = mid; /*mid,而不是mid-1*/
}
else /*此时,x==a[mid],故已找到位置,直接跳出。*/
{
break;
}
}while(low+1 < high);/*low+1==high时,二者相邻,可知pos已找到*/
*pos = high;
}
/*按照你的要求,使用指针实现插入算法。*/
void Insert_X(int x, int pos, int *a)
{
int *p = &(a[len-1]);/*p指向a[]尾部*/
int * const q = &(a[pos]);/*安全起见,将q声明指针常量*/
for(; q<=p; p--){
*(p+1) = *p; /*将a[]中元素逐个后移,腾出1个空间*/
}
*q = x;
len++;
}
/*打印*/
void print_Arr(int *arr)
{
int i=0;
for(; i<len; i++){
printf("%d ",a[i]);
}
printf("\n");
}
程序当场完成,花了1个小时的时间。绝对原创,纯手打!VC6.0调试通过,至于截图,LZ自己运行看吧。
有问题请追问。
#include<stdio.h>
int main()
{
int num,now[100];//num为要输入的数,now数组保存
int len = 5;//假设数组初始长为5
int i, j;
for(i = 0; i<len; i++)
scanf("%d",&now[i]);
for(i = 0; i<len; i++)
printf("%d ",now[i]);
printf("\n");
while(scanf("%d",&num)!=EOF)
{
int *p = now; //p指向数组的首地址
int idx = len;
for(i = 0; i<len; i++)
printf("%d ",*(p+i));
printf("\n");
while(*p>0&&*p<num)
p++;
int *q = p;
while(p+idx>q)
{
*(p+idx) = *(p+idx-1);
idx--;
}
p = q;
*p = num;
len++;
for(i = 0; i<len; i++)
printf("%d ",now[i]);
printf("\n");
}
return 0;
}