Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1589252
  • 博文数量: 354
  • 博客积分: 8137
  • 博客等级: 中将
  • 技术积分: 5137
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-26 15:40
文章分类

全部博文(354)

文章存档

2010年(300)

2009年(54)

分类: C/C++

2010-06-24 21:36:42

#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);
}


阅读(604) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~