#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int binary(char *ptr[], char *str, int n);
void insert(char *prt[], char *str, int n, int i);
char *temp, *ptr1[6];
int i;
printf("请为字符形指针数组赋初值: \n");
for(i = 0; i < 5; i++){
ptr1[i] = (char *)malloc(20);
gets(ptr1[1]);
}
ptr1[5] = (char *)malloc(20);
printf("\n");
printf("original string:\n");
for(i = 0; i < 5; i++)
printf("%s\n",ptr1[i]);
printf("\ninput search string:\n");
temp = (char *)malloc(20);
gets(temp);
i = binary(ptr1, temp, 5);
printf("i = %d\n", i);
insert(ptr1, temp, 5, i);
printf("output strings:\n");
for(i = 0; i < 6; i++)
printf("%s\n",ptr1[i]);
system("pause");
return 0;
}
int binary(char *ptr[], char *str, int n)
{
int hig, low, mid;
low = 0;
hig = n - 1;
if(strcmp(str, ptr[0]) < 0)
return 0;
if(strcmp(str, ptr[hig]) > 0)
return n;
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;
}
return low;
}
void insert(char *ptr[], char *str, int n, int i)
{
int j;
for(j = n; j > i; j--)
strcpy(ptr[j], ptr[j - 1]);
strcpy(ptr[i], str);
}
|