AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > C语言

指针数组

51自学网 2015-09-08 http://www.51zixue.net


[例6-25]对已排好序的字符指针数组进行指定字符串的查找。字符串按字典顺序排列,查找算法采用二分法,或称为折半查找。
折半查找算法描述:
1.设按开序(或降序)输入n个字符串到一个指针数组。
2.设low指向指针数组的低端,high指向指针数组的高端,mid=(low+high)/2
3.测试mid所指的字符串,是否为要找的字符串。
4.若按字典顺序,mid所指的字符串大于要查找的串,表示被查字符串在low和mid之间,
否则,表示被查字符串在mid和high之间。
5.修改low式high的值,重新计算mid,继续寻找。
#include<stdlib.h>
#include<alloc.h>
#include<string.h>
#include<stdio.h>
main()
{
char*binary();/*函数声明*/
char*ptr1[5],*temp;
inti,j;
for(i=0;i<5;i++)
{
ptr1[i]=malloc(20);/*按字典顺序输入字符串*/
gets(ptr1[i]);
}
printf("/n");
printf("original string:/n");
for(i=0;i<5;i++)
printf("%s/n",ptr1[i]);
printf("input search string:/n");
temp=malloc(20);
gets(temp);/输*入被查找字符串*/
i=5;
temp=binary(ptr1,temp,i);/*调用查找函数*/
if(temp)printf("succesful-----%s/n",temp);
elseprintf("nosuccesful!/n");
return;
}
char *binary(char *ptr[],char *str,int定n)义返回字符指针的函数*/
{/*折半查找*/
inthig,low,mid;
low=0;
hig=n-1;
while(low<=hig)
{
mid=(low+hig)/2;
if(strcmp(str,ptr[mid])<0)
hig=mid-1;
elseif(strcmp(str,ptr[mid])>0)
low=mid+1;
else return(str);/*查帐成功,返回被查字符串*/
}
return NULL; / *查找失败,返回空指针* /
}

[例6-26] 在一个已排好序的字符串数组中,插入一个键盘输入的字符串,使其继续保持有序。
在上述程序查找成功的基础上,我们将该字符串插入到字符数组中。插入的位置可以是数组头、中间或数组尾。查找的算法采用折半算法,找到插入位置后,将字符串插入。
#include <stdlib.h>
#include <alloc.h>
#include <string.h>
#include <stdio.h>
m a i n ( )
{
int binary(); / *查找函数声明* /
void insert(); / *插入函数声明* /
char *temp,*ptr1[6];
int i,j;
for (i=0;i<5;i++)
{

ptr1[i]=malloc(20);/*为指针分配地址后*/
gets(ptr1[i]);/*输入字符串*/
}
ptr1[5]=malloc(20);
printf("/n");
printf("original string:/n");
for(i=0;i<5;i++)/*输出指针数组各字符串*/
printf("%s/n",ptr1[i]);
printf("input search string:/n");
temp=malloc(20);
gets(temp);/*输入被插字符串*/
i=binary(ptr1,temp,5)/*;寻找插入位置i*/
printf("i=%d/n",i);
insert(ptr1,temp,5,i);/*在插入位置i处插入字符串*/
printf("outputstrings:/n");
for(i=0;i<6;i++)/*输出指针数组的全部字符串*/
printf("%s/n",ptr1[i]);
return;
}
intbinary(char*ptr[],char*str,intn)
{/*折半查找插入位置*/
int hig,low,mid;
low=0;
hig=n-1;
if(strcmp(str,ptr[0])<0)return0;
/*若插入字符串比字符串数组的第0个小,则插入位置为0*/
if(strcmp(str,ptr[hig])>0)returnn;
/*若插入字符串比字符串数组的最后一个大,则应插入字符串数组的尾部*/
while(low<=hig)
{
mid=(low+hig)/2;
if(strcmp(str,ptr[mid])<0)
hig=mid-1;
else if(strcmp(str,ptr[mid])>0)
low=mid+1;
else return(mid);/*插入字符串与字符串数组的某个字符串相同*/
}
returnlow;/*插入的位置在字符串数组中间*/
}
void insert(char*ptr[],char*str,intn,inti)
{
int j;
for(j=n;j>i;j--)/*将插入位置之后的字符串后移*/
strcpy(ptr[j],ptr[j-1]);
strcpy(ptr[i],str);将被插字符串按字典顺序插入字符串数组*/
}
在程序中,字符串数组的6个指针均分配存放20字节的有效地址。语句ptr1[5]=malloc(20)保证插入字符串后,也具有安全的存储空间,字符串的长度以串中最长的为基准向系统申请存储空间,以保证在串的移动中有足够的存储空间。

 
 
说明
:本教程来源互联网或网友上传或出版商,仅为学习研究或媒体推广,51zixue.net不保证资料的完整性。
 

上一篇:指向指针的指针  下一篇:指针的地址分配